A few years ago I wrote a simple wrapper based on MSDN - AesManaged Class code, to obscure values saved in registry (simply to prevent manual tampering with these, nothing 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 on a valid string. Changing key and iv does not make any difference. Tried executing on several machines - same result. No exceptions are thrown. However, decryption still works fine!
Why does Encrypt( ) suddenly fail? Is there some Windows Update that changed the play-field?
FlushFinalBlockmethod of cryptostream prior to callingms.ToArray(). It doesn't matter if it used to work because if you did it this way it was always wrong. You were just lucky before, now you're not so lucky.msnow has a value (=> so doesenc). But thenDecrypt( )does not reverse it back to original string?! Is there smth missing too? And in general, is it possible to be that lucky for 3 years without a single issue? I still want to find out the exact root cause, any ideas?cs.FlushFinalBlock( );) value returned byEncrypt(..)is the same for any input, provided key and iv are same. As soon as i change either key or iv, result changes! But it ignores the input!? Also, length of the encrypted result was somewhat proportional to length of the input, now it is 24 chars exactly and doesn't change.. What is going on?