C#中的以下AES算法返回的加密值与节点js和CryptoJS返回的值不同。 NodeJS Crypto库和CryptoJS返回相同的值,但.NET的AesCryptoServiceProvider返回不同的值。有什么想法吗?
C#示例
private const string AesIV = @"!QAZ2WSX#EDC4RFV";
private const string AesKey = @"5TGB&YHN7UJM(IK<";
public static void Main()
{
try
{
string original = "HelloWorld";
Console.WriteLine(Encrypt(original));
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
}
}
/// <summary>
/// AES Encryption
/// </summary>
private static string Encrypt(string text)
{
// AesCryptoServiceProvider
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.BlockSize = 128;
aes.KeySize = 128;
aes.IV = Encoding.UTF8.GetBytes(AesIV);
aes.Key = Encoding.UTF8.GetBytes(AesKey);
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
// Convert string to byte array
byte[] src = Encoding.Unicode.GetBytes(text);
// encryption
using (ICryptoTransform encrypt = aes.CreateEncryptor())
{
byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
// Convert byte array to Base64 strings
return Convert.ToBase64String(dest);
}
}
NodeJS示例:
crypto = require "crypto"
algo = 'aes-128-cbc'
keyBuffer = new Buffer("!QAZ2WSX#EDC4RFV")
ivBuffer = new Buffer("5TGB&YHN7UJM(IK<")
cipher = crypto.createCipheriv(algo, keyBuffer, ivBuffer)
textBuffer = new Buffer('HelloWorld')
encrypted = cipher.update(textBuffer)
encryptedFinal = cipher.final()
encryptedText = encrypted.toString('base64') + encryptedFinal.toString('base64')
console.log encryptedText
CryptoJS示例:
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
<script>
var key = CryptoJS.enc.Utf8.parse('!QAZ2WSX#EDC4RFV');
var iv = CryptoJS.enc.Utf8.parse('5TGB&YHN7UJM(IK<');
var encrypted = CryptoJS.AES.encrypt("HelloWorld", key, { iv: iv });
alert(encrypted);
</script>
答案 0 :(得分:3)
您的C#版本使用UTF-16LE将HelloWorld转换为纯文本字节。 NodeJS(也可能是CryptoJS)使用UTF-8字节。在C#one中使用Encoding.UTF8.GetBytes()。
答案 1 :(得分:0)
NodeJS中的默认填充是PKCS5(假设CryptoJS是相同的,因为你说它们产生相同的结果)。您的C#代码正在为PKCS7设置填充。