0 votes
by (140 points)

How can I best decrypt an encrypted string (Rijndael) with REBEX?
Any tips / hints?

Thanks.

1 Answer

0 votes
by (147k points)

Disclaimer: In practice, it's usually best to use higher-level open standards designed for these scenarios (such as Cryptographic Message Syntax provided by Rebex.Common assembly) instead of encrypting/decrypting data directly using low-level cryptographic primitives.

However, if you have a string encrypted directly using one of the supported Rijndael modes, it should be possible to decrypt the input data using Rebex SymmetricKeyAlgorithm class, and convert the resulting byte array to a string using .NET System.Text.Encoding class.

For example, let's say the string has been encrypted using Rijndael encryption in CBC mode, with PKCS #7 padding and with a 128-bit key and IV. So overall, we would have something like this on input:

// encrypted string
var encryptedData = new byte[]
{
    0xF6, 0x94, 0x51, 0xFD, 0x34, 0x67, 0xAD, 0xC0,
    0x76, 0x54, 0xE3, 0x4A, 0x21, 0x83, 0xA9, 0xF8,
    0x53, 0xF4, 0x71, 0x97, 0x67, 0xD7, 0xC0, 0xAB,
    0x59, 0xDC, 0xF6, 0x2B, 0xD0, 0xE9, 0xEE, 0x7F,
};

// charset used by the encrypted string
var encoding = Encoding.UTF8;

// 128-bit key
var key = new byte[]
{
    0xA4, 0x6C, 0xDC, 0x10, 0x15, 0xD6, 0x94, 0xFF,
    0x53, 0xDC, 0x35, 0x68, 0x4C, 0x98, 0x03, 0xEB,
};

// 128-bit initialization vector
var iv = new byte[]
{
    0xBD, 0x1B, 0x28, 0xCE, 0x3E, 0x26, 0x24, 0x3C,
    0xD0, 0x5C, 0x6E, 0x68, 0x69, 0x18, 0xE2, 0x41,
};

// cipher and padding mode
var cipherMode = CipherMode.CBC;
var paddingMode = PaddingMode.PKCS7;

Then, decryption itself will look like this:

// decrypt using AES (a subset of Rijndael)
string decryptedString;
using (var alg = new SymmetricKeyAlgorithm(SymmetricKeyAlgorithmId.AES))
{
    // configure the algorithm
    alg.Mode = cipherMode;
    alg.Padding = paddingMode;
    alg.SetKey(key);
    alg.SetIV(iv);

    // decrypt encrypted data and convert it to a string
    using (ICryptoTransform transform = alg.CreateDecryptor())
    {
        byte[] decryptedData = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
        decryptedString = encoding.GetString(decryptedData);
    }
}

// show the decrypted string
Console.WriteLine("Decrypted string: {0}", decryptedString);
by (140 points)
Hi, Lukas,

many thanks for your answer.
I'll try the suggestion as soon as possible...

-prh
...