NewBee NewBee - 3 months ago 19
C# Question

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:

TJhKuhjyx/87giutBNHh9t==

Answer

Actually the results are the same. They are just encoded differently. Both functions encrypt the input and return binary, which is then encoded for easier storage and transport. The ColdFusion code chooses to encode those bytes as "hex", while the C# code uses "base64". However, while the encoded results may look different, they still represent the same value. Example:

  • CF / Hex: 04197FAA3C9C030660A6377E44F77C4E
  • C# / Base64: BBl/qjycAwZgpjd+RPd8Tg==

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")>