Search code examples
c#encryptioncoldfusion

Convert ColdFusion Encryption using AES/Hex to C#


Related to the topic in this post: Converting Coldfusion encryption code to C#

How would you do the conversion for this:

<!--- valueToEncrypt = "34245678", key = "TJhKuhjyx/87giutBNHh9t==" --->
<cfset output = Encrypt( valueToEncrypt, key, "AES", "Hex")>

Here's what I tried in C#:

byte[] plainText = Encoding.UTF8.GetBytes(TextToEncrypt);
byte[] key = Convert.FromBase64String(encryptionKey);
RijndaelManaged algorithm = new RijndaelManaged();
algorithm.Mode = CipherMode.ECB;
algorithm.Padding = PaddingMode.PKCS7;
algorithm.BlockSize = 128;
algorithm.KeySize = 128;
algorithm.Key = key;
string result;
using (ICryptoTransform encryptor = algorithm.CreateEncryptor())
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
        {
            cryptoStream.Write(plainText, 0, plainText.Length);
            cryptoStream.FlushFinalBlock();
            result = Convert.ToBase64String(memoryStream.ToArray());
        }
    }
}

return result;

ColdFusion Result:

04197FAA3C9C030660A6377E44F77C4E

C# Result:

BBl/qjycAwZgpjd+RPd8Tg==

Solution

  • Actually the results are the same. They are just encoded differently. Both encrypt the input and generate binary, then encode the result for easier storage and transport. The ColdFusion code just chooses to encode those bytes as "hex", while the C# code uses "base64". While the results may look different, they still represent the same value. For example, notice if you decode the C# result (base64) into binary and re-encode it as hex, it matches the CF result?

    C# (Convert result from base64 to hex)

    byte[] decoded = Convert.FromBase64String("BBl/qjycAwZgpjd+RPd8Tg==");
    string resultAsHex = (BitConverter.ToString(decoded).Replace("-", string.Empty));
    

    Result:

    04197FAA3C9C030660A6377E44F77C4E 
    

    Having said that, if you need to produce the same encoded string on both sides, either:

    A. Change the C# code to encode the result as hex, instead of base64

        result =  BitConverter.ToString(memoryStream.ToArray()).Replace("-", string.Empty);
    

    OR

    B. Change the CF code to use base64 encoding:

        <cfset output = Encrypt( valueToEncrypt, key, "AES", "Base64")>