Skip to content

Commit

Permalink
Fix for AES cypher in .Net 5.
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisg32 committed Apr 27, 2021
1 parent 57c80cb commit c3fa8d9
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions Commons/Util/StringCipher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,15 @@ public static string Encrypt(string plainText, string passPhrase)
// Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
// so that the same Salt and IV values can be used when decrypting.
var saltStringBytes = Generate256BitsOfRandomEntropy();
var ivStringBytes = Generate256BitsOfRandomEntropy();
var ivStringBytes = Generate128BitsOfRandomEntropy();
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var symmetricKey = Aes.Create())
{
symmetricKey.BlockSize = 256;
//https://stackoverflow.com/questions/9300340/got-error-specified-block-size-is-not-valid-for-this-algorithm-while-initiali
symmetricKey.BlockSize = 128;
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
Expand Down Expand Up @@ -98,5 +99,16 @@ private static byte[] Generate256BitsOfRandomEntropy()
}
return randomBytes;
}

private static byte[] Generate128BitsOfRandomEntropy()
{
var randomBytes = new byte[16]; // 16 Bytes will give us 128 bits.
using (var rngCsp = RandomNumberGenerator.Create())
{
// Fill the array with cryptographically secure random bytes.
rngCsp.GetBytes(randomBytes);
}
return randomBytes;
}
}
}

0 comments on commit c3fa8d9

Please sign in to comment.