使用AES /十六进制将ColdFusion加密转换为C#
作者:互联网
与这篇文章中的主题相关:
Converting Coldfusion encryption code to C#
您将如何进行此转换:
<!--- valueToEncrypt = "34245678", key = "TJhKuhjyx/87giutBNHh9t==" --->
<cfset output = Encrypt( valueToEncrypt, key, "AES", "Hex")>
这是我在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结果:
04197FAA3C9C030660A6377E44F77C4E
C#结果:
BBl/qjycAwZgpjd+RPd8Tg==
解决方法:
实际上结果是相同的.它们只是编码不同.两者都对输入进行加密并生成二进制文件,然后对结果进行编码,以便于存储和传输. ColdFusion代码仅选择将这些字节编码为“十六进制”,而C#代码使用“ base64”.尽管结果看起来可能有所不同,但它们仍表示相同的值.例如,请注意,如果将C#结果(base64)解码为二进制和re-encode it as hex,它是否与CF结果匹配?
C#(将结果从base64转换为十六进制)
byte[] decoded = Convert.FromBase64String("BBl/qjycAwZgpjd+RPd8Tg==");
string resultAsHex = (BitConverter.ToString(decoded).Replace("-", string.Empty));
结果:
04197FAA3C9C030660A6377E44F77C4E
话虽如此,如果您需要在两边都产生相同的编码字符串,则可以:
A.将C#代码更改为encode the result as hex,而不是base64
result = BitConverter.ToString(memoryStream.ToArray()).Replace("-", string.Empty);
要么
B.更改CF代码以使用base64编码:
<cfset output = Encrypt( valueToEncrypt, key, "AES", "Base64")>
标签:encryption,coldfusion,c 来源: https://codeday.me/bug/20191026/1938733.html