Elisabeth
Elisabeth

Reputation: 21206

Same encrypted Text with AES must result in different length

I use this sample code: https://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged.aspx

The AESCryptor is my own class with the original code from the above msdn link. It just wraps the Decrypt/encrypt methods NOT more.

Thats how I call the decrypt/encrypt methods:

string plainText1 = "This is my sample plain text";
string plainText2 = "This is my sample plain text";

// Create a new instance of the AesManaged
// class.  This generates a new key and initialization 
// vector (IV).
using (AesManaged myAes = new AesManaged())
{
    // Encrypt the string to an array of bytes.
    byte[] encrypted = AESCryptor.EncryptStringToBytes_Aes(plainText1, myAes.Key, myAes.IV);

    byte[] encrypted2 = AESCryptor.EncryptStringToBytes_Aes(plainText2, myAes.Key, myAes.IV);

}

My result that I expect is that both (encrypted and encrypted2) byte arrays have of course the same length but gets filled up with "zeros" so when I encode the byte[] with Base64 I get different looking strings.

How can I do that? Setting myAes.Padding = PaddingMode.Zeros; Did not help.

Upvotes: 0

Views: 767

Answers (1)

Rawling
Rawling

Reputation: 50114

In order to get different results for the same key and plaintext, you need to use a different IV.

By the look of it, to do this with a single AesManaged instance, you need to call myAes.GenerateIV() between your two encryption calls.

If you create a new AesManaged, you get a new key and a new IV for free, which may also achieve what you want.

Don't forget to record your key and IVs, because you won't be able to decrypt your messages without them.

Upvotes: 2

Related Questions