将库Org.BouncyCastle.Crypto用于 C# 项目,将crypto-js用于 JS 项目。
尝试通过 C# 加密数据,该 C# 使用以下函数输出字符串:
public string EncryptData(string data)
{
byte[] inputBytes = Encoding.UTF8.GetBytes(data);
byte[] keyBytes = Encoding.UTF8.GetBytes(ENCRYPTION_KEY);
IBufferedCipher cipher = CipherUtilities.GetCipher("AES/CTR/NoPadding");
cipher.Init(true, new ParametersWithIV(ParameterUtilities.CreateKeyParameter("AES", keyBytes), new byte[16]));
byte[] encryptedBytes = cipher.DoFinal(inputBytes);
string base64EncryptedOutputString = Convert.ToBase64String(encryptedBytes);
return base64EncryptedOutputString;
}
然后在JS中使用下面的函数来解密:
function decrypt(text) {
var decipher = crypto.createDecipher(algorithm, password);
var dec = decipher.update(text, "hex", "utf8");
dec += decipher.final("utf8");
return dec;
}
下面是通过 JS 加密的函数,以防它有助于尝试使 C# 代码与 JS 代码相同(而不是相反):
function encrypt(text) {
var cipher = crypto.createCipher(algorithm, password);
var crypted = cipher.update(text, "utf8", "hex");
crypted += cipher.final("hex");
return crypted;
}
当它应该返回输入的原始数据时,解密函数似乎返回了一个空字符串。
有什么想法可能是这里的问题吗?