试图将下面的C#代码转换为nodeJS,但是结果不一样。这里需要一些帮助:C#代码:
public static string Encrypt(string clearText)
{
string EncryptionKey = "abcdef";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new
Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
在JS中尝试的代码:
const crypto = require('crypto'),
algorithm = 'aes-256-cbc',
secret = 'abcdef',
keystring = crypto.createHash('sha256').update(String(secret)).digest('base64').substr(0, 32);
iv = crypto.createHash('sha256').update(String(secret)).digest('base64').substr(0, 16);
inputEncoding = 'utf8',
outputEncoding = 'base64';
function encrypt(text) {
let cipher = crypto.createCipheriv('aes-128-cbc', keystring, iv);
let encrypted = cipher.update(text, inputEncoding, outputEncoding);
encrypted += cipher.final(outputEncoding);
return encrypted;
}
在节点js中寻找兼容版本
PBKDF2的参数为:
const secret = 'abcdef';
const salt = Buffer.from([0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76]);
const iterations = 1000;
const length = 32 + 16;
const digest = 'sha1';
const keyIV = crypto.pbkdf2Sync(secret, salt, iterations, length, digest);
的前32个字节keyIV
是密钥,其后的16个字节是IV:
const key = keyIV.slice(0, 32);
const iv = keyIV.slice(32, 32 + 16);
在该encrypt
方法中,必须将UTF-16LE用作输入编码(utf16le
)和aes-256-cbc
算法/模式:
const inputEncoding = 'utf16le';
const outputEncoding = 'base64';
const algorithm = 'aes-256-cbc';
function encrypt(text) {
let cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(text, inputEncoding, outputEncoding);
encrypted += cipher.final(outputEncoding);
return encrypted;
}
测试:
console.log(encrypt("The quick brown fox jumps over the lazy dog")); // u9JQyr8G0FbU1D+TF1ZmXNK8cMZjhL7xbhYitmXVaWNDu1hDiBY6TNUjKcza4fX99xN0f1tT3qSNHMGWTV8o2QkDnVqNQai07qAX4R2iSW/j4E8CKGwVOCWnQ46HbfWs
根据C#代码的结果。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句