C# and ColdFusion AES Encryption not matching

自作多情 提交于 2019-12-23 01:43:26

问题


I have to encrypt url query sting in C# and pass to ColdFusion page. Can someone help me on writing encryption code using AES algorithm in C#.net that is equivalent to below ColdFusion function? Thanks in advance.

<cfset strLink = Encrypt("top secret", "WTq8zYcZfaWVvMncigHqwQ==", "AES","Hex")>

CF Result:

  • strLink = 91E72250B8A7EDBC4E5AF37F04E6AB5B

I tried below code in C#, but the results are not matching.

        byte[] plainText = Encoding.Unicode.GetBytes("top secret");

        byte[] key = Convert.FromBase64String("WTq8zYcZfaWVvMncigHqwQ==");
        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;

C# Result:

  • HEX = 89F9F3C55CD232362FE1E14240C479BE5B56210FF3913E7B6BA4BCD3C87F9AA7
  • Base64 = ifnzxVzSMjYv4eFCQMR5vltWIQ/zkT57a6S808h/mqc=

回答1:


(From comments...)

This is a perfect example of how character encoding makes a big difference.

Believe it or not, it is simply due to using the wrong encoding in the C# code. Encoding.Unicode uses UTF-16, whereas CF's Encrypt function always uses UTF-8 (very different). Consequently, the C# code is encrypting a totally different value than CF. Hence the different results, and why the length of the C# string (hex) is longer than the one returned from CF.

Use Encoding.UTF8.GetBytes() instead of Encoding.Unicode.GetBytes() and the results will match:

byte[] plainText = Encoding.UTF8.GetBytes("top secret");


来源:https://stackoverflow.com/questions/31945755/c-sharp-and-coldfusion-aes-encryption-not-matching

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