我正在尝试使用 3DES ECB 将 C# 代码转换为加密文本(您可以将其复制并粘贴到https://dotnetfiddle.net/上以运行它)
using System;
using System.Configuration;
using System.Security.Cryptography;
using System.Text;
public class Program
{
public static void Main()
{
string toEncrypt = "testtext";
string key = "testkey";
bool useHashing = true;
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
System.Configuration.AppSettingsReader settingsReader =
new AppSettingsReader();
key = string.IsNullOrEmpty(key) ? (string)settingsReader.GetValue("SecurityKey", typeof(String)) : key;
if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
}
else
{
keyArray = UTF8Encoding.UTF8.GetBytes(key);
}
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
key = Convert.ToBase64String(keyArray, 0, keyArray.Length);
Console.WriteLine(key);
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
Console.Write(Convert.ToBase64String(resultArray, 0, resultArray.Length));
}
}
输出:
Ihs2jX9fWXhn9SWXHyj/dQ== <- md5 secret key
wHL9J7vhm9LZI2W5DQJGKw== <- encrypt result
所以我在 NodeJS 中重写了上面的代码以使用加密
const crypto = require('crypto');
const md5 = text => {
return crypto
.createHash('md5')
.update(text)
.digest('base64');
}
const encrypt = (text, secretKey) => {
secretKey = md5(secretKey);
console.log(secretKey);
const cipher = crypto.createCipher('des-ede3', secretKey);
const encrypted = cipher.update(text, 'utf8', 'base64');
return encrypted + cipher.final('base64');
};
const encrypted = encrypt('testtext', 'testkey');
console.log(encrypted);
输出:
Ihs2jX9fWXhn9SWXHyj/dQ== <- md5 secret key
VNa9fDYgPus5IMhUZRI+jQ== <- encrypt result
我认为问题在于使用 3DES ECB 的 C# 和 NodeJS Crypto 方法。知道如何在 NodeJS中复制 C# 代码行为吗?