Note that there are some explanatory texts on larger screens.

plurals
  1. POCryptographicException when using RijndaelManaged
    text
    copied!<p>I am trying to encrypt a string of text using the RijndaelManaged class in .NET. However, I keep getting a CryptographicException ("Length of the data to decrypt is invalid"). This message isn't exactly helpful, especially since its happening when I attempt to ENCRYPT data, not decrypt. Below is the code.</p> <pre><code>public static string EncryptKMSToken(string valueToEncrypt, string encryptionKey) { string results = string.Empty; using (RijndaelManaged aes = new RijndaelManaged()) { aes.BlockSize = 128; aes.KeySize = 128; aes.Padding = PaddingMode.PKCS7; aes.Mode = CipherMode.CBC; UTF8Encoding byteTransform = new UTF8Encoding(); aes.Key = byteTransform.GetBytes(encryptionKey); ICryptoTransform encryptor = aes.CreateDecryptor(aes.Key, aes.IV); using (MemoryStream stream = new MemoryStream()) { using (CryptoStream encryptStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write)) { using (StreamWriter writer = new StreamWriter(encryptStream)) { writer.Write(valueToEncrypt); } byte[] encryptedBytes = stream.ToArray(); results = byteTransform.GetString(encryptedBytes); } } } return results; } </code></pre> <p>The error happens when the 3rd using statement closes (i.e. the line after writer.Write(valueToEncrypt). If I try to move the two lines below that inside the third using block, I end up with an empty string (and the error still happens). I pulled this code directly off of this site (http://stackoverflow.com/questions/273452/using-aes-encryption-in-c-sharp) but it doesn't seem to work. Does anyone have any ideas?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload