Shane McGarry
Shane McGarry

Reputation: 547

CryptographicException when using RijndaelManaged

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.

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;
}

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?

Upvotes: 2

Views: 578

Answers (1)

Maarten Bodewes
Maarten Bodewes

Reputation: 94058

Yes, but I think you will too if you reread your code:

ICryptoTransform encryptor = aes.CreateDecryptor(aes.Key, aes.IV);

That's a decryptor named as an encryptor...

Upvotes: 3

Related Questions