简体   繁体   English

使用 AES 时,Crypto-js 每次运行时都会返回不同的值

[英]Crypto-js returns different values every time it's run when using AES

I'm trying to encrypt something using crypto-js and using the AES type of encryption.我正在尝试使用 crypto-js 和使用 AES 类型的加密来加密一些东西。

The problem i'm having is that my encrypted value is different every time I encrypt it.我遇到的问题是每次加密时我的加密值都不同。

With this simple example, I run the same encryption 5 different times and I get 5 different results.在这个简单的例子中,我运行相同的加密 5 次,得到 5 种不同的结果。 Wtf is going on here?这里发生了wtf?

task.js任务.js

var AES = require('crypto-js/aes');
var key = "abc123";
var secret = "encryptThisWord";

console.log(AES.encrypt(secret, key).toString());
console.log(AES.encrypt(secret, key).toString());
console.log(AES.encrypt(secret, key).toString());
console.log(AES.encrypt(secret, key).toString());
console.log(AES.encrypt(secret, key).toString());

在此处输入图片说明

Check the contents of AES.encrypt(secret, key) - it is an object with a number of fields, iv and salt of particular interest ( jsFiddle ).检查AES.encrypt(secret, key) - 它是一个具有许多字段、特别感兴趣的ivsalt ( jsFiddle ) 的对象。

Each time you run the AES.encrypt crypto-js chooses new IV and new salt (you can supply your own values, by the way).每次运行AES.encrypt crypto-js 时,都会选择新的 IV 和新的盐(顺便说一下,您可以提供自己的值)。 Random IV means that output will be different even with the same key, and random salt means that the actual encryption key is different too, because it is derived from the the passphrase and salt.随机IV意味着即使使用相同的密钥输出也会不同,随机盐意味着实际的加密密钥也不同,因为它是从密码和盐派生出来的。

You may (actually, should) ask why the first ten Base64 output characters are the same when both the encryption key and IV are different?您可能(实际上,应该)问为什么在加密密钥和 IV 不同的情况下,前十个 Base64 输出字符是相同的? That is because calling toString() on the ecnryption result converts it into "OpenSSL-compatible string", which is basically Base64("Salted__" + salt + ciphertext) , where "Salted__" is the constant prefix which, of course, leads the same prefix in the Base64 output.那是因为在加密结果上调用toString()会将其转换为“OpenSSL-compatible string”,基本上是Base64("Salted__" + salt + ciphertext) ,其中"Salted__"是常量前缀,当然,导致Base64 输出中的相同前缀。

I faced the same issue.我遇到了同样的问题。 This is simply due to us not knowing the working of algorithm.这仅仅是因为我们不知道算法的工作原理。 Simply put, the key and IV are different for each call of the encrypt method, as mentioned in the above answer.简单来说,加密方法每次调用的key和IV都是不同的,如上面的回答中提到的。

To ensure the exact same value for each iteration - you can refer to this answer https://stackoverflow.com/a/47096284/4098272为确保每次迭代的值完全相同 - 您可以参考此答案https://stackoverflow.com/a/47096284/4098272

Alternatively, you can use the SHA3 function and compare the two Hash values.或者,您可以使用 SHA3 函数并比较两个哈希值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM