【发布时间】:2019-06-20 10:56:22
【问题描述】:
我正在尝试将 node 中制作的加密代码迁移到 .net。
这是节点:
function GenerateTokenByLit(literal) {
const text_encrypt = Buffer.from(literal, 'utf8');
const cipher = crypto.createCipheriv('aes-256-ecb', Buffer.from(SECRET_KEY, 'utf8'), '');
cipher.setAutoPadding(true);
const text = cipher.update(text_encrypt, 'buffer', 'base64');
return text + cipher.final('base64');
}
.NET 代码:
public static string Encrypt(string original)
{
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
byte[] KEY = Encoding.UTF8.GetBytes(SECRET_KEY);
byte[] encrypted;
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Padding = PaddingMode.None;
aesAlg.Mode = CipherMode.ECB;
aesAlg.KeySize = 256;
// Create the streams used for encryption.
//const cipher = crypto.createCipheriv('aes-256-ecb', Buffer.from(constants.API_ENVRYPTED_KEY, 'utf8'), '');
//cipher.setAutoPadding(true);
using (ICryptoTransform encryptor = aesAlg.CreateEncryptor(KEY, iv))
using (MemoryStream msEncrypt = new MemoryStream())
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
var bytes = Encoding.ASCII.GetBytes(original);
swEncrypt.Write(bytes);
}
encrypted = msEncrypt.ToArray();
}
}
return System.Convert.ToBase64String(encrypted);
}
我认为问题出在自动填充上。在node里面有两个选项,false或者true,但是在.NET里面有更多选项,反正我都测试过了,没有结果不匹配。
【问题讨论】:
-
Encoding.ASCII.GetBytes(original) 不正确,必须是 Encoding.UTF8 才能匹配节点代码。