How to decrypt a Rijndael 128 encrypted text

3.8k Views Asked by At

I'm trying to decrypt a Rijndael-128 encrypted cipher, these are the values:

Cipher: "QfJzZ9V6Jm43jYPiVaXP9mu+f88S/JC24saHbOMxxC8="
Key: "45744855535472525844494538555934",
Mode: CBC

Result should be: "abcd@1234"

This website seems to decrypt the cipher just fine: https://codebeautify.org/encrypt-decrypt

I'm trying to do the same thing in C# with absolutely no luck, what am I missing here?

class Program
{
    static void Main(string[] args)
    {
        var text = Decrypt("QfJzZ9V6Jm43jYPiVaXP9mu+f88S/JC24saHbOMxxC8=", Convert.FromBase64String("45744855535472525844494538555934"));
    }

    public static string Decrypt(string Text, byte[] keyBytes)
    {
        var textBytes = Convert.FromBase64String(Text);

        var rijKey = new RijndaelManaged();

        rijKey.IV = textBytes.Take(rijKey.BlockSize / 8).ToArray(); 

        rijKey.Padding = PaddingMode.None;

        rijKey.Mode = CipherMode.CBC;

        var  decryptor = rijKey.CreateDecryptor(keyBytes, rijKey.IV);

        var memoryStream = new MemoryStream(textBytes);

        var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);

        var pTextBytes = new byte[textBytes.Length];

        var decryptedByteCount = cryptoStream.Read(pTextBytes, 0, pTextBytes.Length);

        memoryStream.Close();

        cryptoStream.Close();

        string plainText = Encoding.UTF8.GetString(pTextBytes, 0, decryptedByteCount);

        return plainText;
    }
}
1

There are 1 best solutions below

9
Mitch Wheat On

The problem with your code is this line:

rijKey.GenerateIV();

You need the original IV. You can't just use a random one.

If you go to the site you linked to, each time you press encrypt with the key and text you have given, you get a different encrypted text (because a random IV is used). The web page must be prepending the random IV used to encrypt to the encrypted text (or less likely, the web page is storing it), which is why it can then decrypt the encrypted text.

[Your code also needs using statements.]

Is it possible to NOT use the IV when implementing Rijndael decryption?

How to Use Rijndael ManagedEncryption with C#