使用CryptoJS加密和Aes Manager解密

时间:2018-01-10 21:49:01

标签: javascript c# encryption aes cryptojs

我使用CryptoJS加密邮件并将其发送到服务器,并使用Aes Manager在C#的另一端解密。我把它发送到服务器后得到回复,但它不正确。

使用Javascript:

this.CryptoJS=require("crypto-js");
var temp=this.CryptoJS.AES.encrypt("hello","yyyyyyyyyyyyyyyyyyyyyyyyyyyyykey",{
  keySize:128/8,
  iv:this.CryptoJS.enc.Utf8.parse("helllooohelllooo"),
  mode:this.CryptoJS.mode.CBC,
  padding:this.CryptoJS.pad.ZeroPadding
});
data.text=temp.toString(); // This is how I send it to the server

C#:

byte[] Key = UTF8Encoding.UTF8.GetBytes("yyyyyyyyyyyyyyyyyyyyyyyyyyyyykey");
byte[] toBytes = UTF8Encoding.UTF8.GetBytes("helllooohelllooo");
AesManaged aes = new AesManaged();
aes.Key = Key;
aes.IV = toBytes;
aes.Padding = PaddingMode.Zeros;
aes.Mode = CipherMode.CBC;
aes.KeySize = 128;
aes.BlockSize = 128;
byte[] bytes = Convert.FromBase64String(data.text);
UTF8Encoding utf8 = new UTF8Encoding();

using (ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
{
    MemoryStream MS = new MemoryStream(bytes);
    CryptoStream CS = new CryptoStream(MS, decryptor, CryptoStreamMode.Write);
    CS.Write(bytes, 0, bytes.Length);
    CS.FlushFinalBlock();
    MS.Position = 0;
    bytes = new byte[MS.Length];
    MS.Read(bytes, 0, bytes.Length);
    Plaintext = utf8.GetString(bytes);
    var temp = 5;
}

这是我从Plaintext变量得到的结果:t�k�\a``\u007f��Ü����\f^,F~\u0017�\u001fp��#5�\u007f\\

2 个答案:

答案 0 :(得分:1)

您应该明确地将密钥,明文和IV作为二进制数据而不是字符串传递:

let iv = CryptoJS.enc.Utf8.parse("helllooohelllooo");
let pt = CryptoJS.enc.Utf8.parse("hello");
let key = CryptoJS.enc.Utf8.parse("yyyyyyyyyyyyyyyyyyyyyyyyyyyyykey");

然后在代码中使用:

CryptoJS.AES.encrypt(pt, key, ...);

请注意,使用零填充,固定IV以及无HMAC或AEAD模式会使您完全不安全的代码。你绝对不应该使用它。有关JavaScript和C#之间安全加密的示例,请参阅this GitHub repository

答案 1 :(得分:0)

我能够解决我的问题我没有将原始密钥转换为utf8而且一旦我这样做就修复了自己

Resource