I'm upgrading the .NET version of our C# solution, and now it's giving me the SYSLIB0021 warning. I'd like to update the code rather than ignore the message. I have to retain original functionality though since there are stored files that I still need to be able to decrypt.
Here's the original code:
var bytes = Convert.FromBase64String(base64Str);
var decryptor = new AesManaged();
var init = MyInit();
byte[] initB = new UTF8Encoding().GetBytes(init);
var rfc = new Rfc2898DeriveBytes(init, initB);
decryptor.Key = rfc.GetBytes(16);
decryptor.IV = rfc.GetBytes(16);
decryptor.BlockSize = 128;
using (MemoryStream cryptoStream = new MemoryStream())
using (CryptoStream cs = new CryptoStream(cryptoStream, decryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(bytes, 0, bytes.Length);
cs.FlushFinalBlock();
cryptoStream.Position = 0;
using (MemoryStream compressedStream = new MemoryStream())
{
cryptoStream.CopyTo(compressedStream);
compressedStream.Flush();
compressedStream.Position = 0;
using (var zip = new DeflateStream(compressedStream, CompressionMode.Decompress))
{
zip.CopyTo(stream);
stream.Position = 0;
}
}
}
When I make the changes that Microsoft suggests on their site (as shown below), and then I try to decrypt one of the existing files, the data doesn't decrypt properly. I'm not sure what I'm doing wrong. I can't simply call the Aes.Create("AesManaged") constructor because that too is obsolete.
Here's my attempted refactor
var bytes = Convert.FromBase64String(base64Str);
var decryptor = Aes.Create();
var init = MyInit();
byte[] initB = new UTF8Encoding().GetBytes(init);
var rfc = new Rfc2898DeriveBytes(init, initB, 1000, HashAlgorithmName.SHA1);
decryptor.Key = rfc.GetBytes(16);
decryptor.IV = rfc.GetBytes(16);
decryptor.BlockSize = 128;
using (MemoryStream cryptoStream = new MemoryStream())
using (CryptoStream cs = new CryptoStream(cryptoStream, decryptor.CreateDecryptor(decryptor.Key, decryptor.IV), CryptoStreamMode.Write))
{
cs.Write(bytes, 0, bytes.Length);
cs.FlushFinalBlock();
cryptoStream.Position = 0;
using (MemoryStream compressedStream = new MemoryStream())
{
cryptoStream.CopyTo(compressedStream);
compressedStream.Flush();
compressedStream.Position = 0;
using (var zip = new DeflateStream(compressedStream, CompressionMode.Decompress))
{
zip.CopyTo(stream);
stream.Position = 0;
}
}
}
As Maarten Bodewes mentioned, I just needed to move the BlockSize assignment to happen before setting the Key and IV, or just remove it entirely since the default is 128 anyway.