转换ColdFusion加密使用AES/十六进制到c#
本文关键字:十六进制 AES ColdFusion 加密 密使 转换 | 更新日期: 2023-09-27 18:04:49
与本文主题相关:将Coldfusion加密代码转换为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)解码为二进制并将其重新编码为十六进制,它是否与CF结果匹配?
c# (将结果从base64转换为十六进制)
byte[] decoded = Convert.FromBase64String("BBl/qjycAwZgpjd+RPd8Tg==");
string resultAsHex = (BitConverter.ToString(decoded).Replace("-", string.Empty));
结果:04197FAA3C9C030660A6377E44F77C4E
话虽如此,如果需要在两边生成相同的编码的字符串,可以:
。更改c#代码,将结果编码为十六进制,而不是base64
result = BitConverter.ToString(memoryStream.ToArray()).Replace("-", string.Empty);
或
B。将CF代码更改为使用base64编码:
<cfset output = Encrypt( valueToEncrypt, key, "AES", "Base64")>