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!
Astrogator
source share