Search code examples
c#.netencryptionrijndaelmanaged

Why is cipher text returned from RijndaelManaged different each time?


I would like to use RijndaelManaged to encrypt a string with any salting so if I pass encrypt a string using the same key I will receive the same cipher text back. The method I am calling looks like this

     public static string GetEncryptedData(string plainText)
    {
        var cipher = new RijndaelManaged();

        string keyString = "really long string"

        var key = Encoding.UTF8.GetBytes(keyString);
        cipher.Padding = PaddingMode.Zeros;
        cipher.Mode = CipherMode.ECB;
        cipher.KeySize = 256;
        cipher.BlockSize = 256;

        var cryptoTransform = cipher.CreateEncryptor();
        byte[] stuffToEncrypt = Encoding.UTF8.GetBytes(plainText);
        byte[] cipherText = cryptoTransform.TransformFinalBlock(stuffToEncrypt, 0, plainText.Length);

        return Convert.ToBase64String(cipherText);
    }

I thought if I set

cipher.Padding = PaddingMode.Zeros;
cipher.Mode = CipherMode.ECB;

There would be no randomness introduced and the result will be the same each time this method is called with the same input like

GetEncryptedData("somestring")

but each time it runs it returns a diff value. What am I missing?

Edit

as pointed out on the accepted answer I forgot to set the key so adding this did the trick

cipher.Key = Convert.FromBase64String("C53wafJw3QmImGBN8Se9EnIJgiQq7LyoWHzUEFQI/B0=");

Solution

  • Because you're not setting the key, a different key is generated every time you call your method, so you get a different cipher text. You should set the Key property explicitly so that you're always using the same key.