To securely encrypt a value like a string or integer, you can use symmetric or asymmetric encryption. To encrypt data with a symmetric-key algorithm, you can use the Advanced Encryption Standard (AES). In the next example, we create a new instance of the Aes class and use it to generate a new key and initialization vector (IV). We use the AES to encrypt any type of managed stream. The stream is then wrapped with CryptoStream.
C#
Copy
Aes aes = Aes.Create();
CryptoStream cryptStream = new CryptoStream(fileStream,
aes.CreateEncryptor(aes.Key, aes.VI),
CryptoStreamMode. Write);
Hashing
Hashing is a one-way operation. When you’re using a hashing function to hash nonunique inputs such as passwords, use a salt value added to the original value before hashing.
C#
Copy
public static byte[] HashPassword256(string password)
{
System.Security.Cryptography.SHA256 mySHA256 = System.Security.Cryptography.SHA256.Create();
var encoding = new System.Text.UnicodeEncoding();
return mySHA256.ComputeHash(encoding.GetBytes(password));
}
Random numbers
Temporary password or access codes are intended to be unique per user. You can achieve this uniqueness by introducing random-character generation, and it’s worth noting how the randomness is achieved. You might be familiar with the System.Random class. System.Random is a deterministic pseudo-random sequence generator. It’s predictable and seeded only from the system clock, which means it’s guessable. As a matter of fact, Microsoft Learn documentation explicitly states that you shouldn’t use it for generating passwords. To generate a cryptographically secure random number that’s suitable for creating a random password, you should use a RandomNumberGenerator instance.
C#
Copy
var randomNumberGenerator = System.Security.Cryptography.RandomNumberGenerator.Create();
By using RandomNumberGenerator, you can eliminate the chances of two or more users ending up with the same token or password when they must be unique.
java ee enterprise edition training courses malaysia
Leave a Reply