与此帖子中的主题相关: 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==
答案 0 :(得分:4)
实际上的结果是相同的。它们的编码方式不同。两者都加密输入并生成二进制文件,然后对结果进行编码以便于存储和传输。 ColdFusion代码只选择将这些字节编码为“hex”,而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
话虽如此,如果你需要在两边都生成相同的编码字符串,可以:
一个。将C#代码更改为encode the result as hex,而不是base64
result = BitConverter.ToString(memoryStream.ToArray()).Replace("-", string.Empty);
OR
B中。更改CF代码以使用base64编码:
<cfset output = Encrypt( valueToEncrypt, key, "AES", "Base64")>