AesManaged started generating zero string encryption result after many years of working fine

A few years ago I wrote a simple shell based on MSDN - AesManaged Class , to hide the values ​​stored in the registry (just to prevent manually falsifying them, no more):

public static string Encrypt( string s, byte[] key, byte[] iv ) { byte[] enc; using( AesManaged aes = new AesManaged( ) ) { ICryptoTransform ict = aes.CreateEncryptor( key, iv ); using( MemoryStream ms= new MemoryStream( ) ) using( CryptoStream cs= new CryptoStream( ms, ict, CryptoStreamMode.Write ) ) using( StreamWriter sw= new StreamWriter( cs ) ) { sw.Write( s ); enc = ms.ToArray( ); } } return Convert.ToBase64String( enc ); } public static string Decrypt( string p, byte[] key, byte[] iv ) { string s= null; using( AesManaged aes = new AesManaged( ) ) { ICryptoTransform ict = aes.CreateDecryptor( key, iv ); using( MemoryStream ms= new MemoryStream( Convert.FromBase64String( p ) ) ) using( CryptoStream cs= new CryptoStream( ms, ict, CryptoStreamMode.Read ) ) using( StreamReader sr= new StreamReader( cs ) ) { s= sr.ReadToEnd( ); } } return s; } 

These methods worked perfectly all this time .. until yesterday, when Encrypt produced a null result in a valid string. Changing key and iv is irrelevant. Tried to execute on several machines - the same result. No exceptions are thrown. However, decryption still works fine!

Why Encrypt( ) fail unexpectedly? Is there a Windows Update that changed the playing field?

0
encryption
source share
1 answer

After searching and studying several similar questions ( Aes decryptor gives an empty string ; Using AES encryption in .NET - CryptographicException saying indentation is invalid and cannot be deleted ; Filling is invalid and cannot be deleted using AesManaged ; Filling is invalid and cannot The exception when decrypting a string using "AesManaged" C # ) and looking at my code again, I noticed a difference with the MSDN sample. Indeed, I did the optimization, and this is what broke the execution! The code should be written as follows:

 public static string Encrypt( string s, byte[] key, byte[] iv ) { byte[] enc; using( AesManaged aes = new AesManaged( ) ) { ICryptoTransform ict = aes.CreateEncryptor( key, iv ); using( MemoryStream ms= new MemoryStream( ) ) { using( CryptoStream cs= new CryptoStream( ms, ict, CryptoStreamMode.Write ) ) { using( StreamWriter sw= new StreamWriter( cs ) ) { sw.Write( s ); } } enc = ms.ToArray( ); } } return Convert.ToBase64String( enc ); } 

Note the presence of braces after each using(..) ! Yes, that means CryptoStream is closed - and therefore cleared - before I try to use the buffer, making this approach safe.

I don’t know why the @GregS and @HansPassant solution didn’t, but since the code is working now (reverting to the original version :), my problem is closed. Thank God for version control! :))

Thank you guys for helping me with the solution!

+2
source share

All Articles