Convert ColdFusion Encryption using AES/Hex to C#

混江龙づ霸主 提交于 2020-01-13 16:25:32

问题


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==

回答1:


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


来源:https://stackoverflow.com/questions/39230309/convert-coldfusion-encryption-using-aes-hex-to-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!