[英]How to generate the same AES encrypted message in crypto-js?
I tried setting iv or not setting iv, but encrypted messages were always different.我尝试设置 iv 或不设置 iv,但加密的消息总是不同的。
import CryptoJS from "crypto-js";
const iv = CryptoJS.lib.WordArray.create([0x20212223, 0x24252627, 0x28292a2b, 0x2c2d2e2f]);
const a = CryptoJS.AES.encrypt("my message", "my secret", {iv: iv}).toString();
console.log(a);
Some outputs were U2FsdGVkX1/7vfxMQ5nTdcBqjLjirF5LutKPUpPKkxI=
, U2FsdGVkX18+075efZU5tMZyIziirm0e6O6u4ZPXVcA=
一些输出是U2FsdGVkX1/7vfxMQ5nTdcBqjLjirF5LutKPUpPKkxI=
, U2FsdGVkX18+075efZU5tMZyIziirm0e6O6u4ZPXVcA=
"my secret" is a password, not a key. “我的秘密”是密码,而不是密钥。 CryptoJS.AES.encrypt
is doing a key derivation function (internally) to derive a key from the password. CryptoJS.AES.encrypt
正在执行密钥派生 function(内部)以从密码中派生密钥。 One of the inputs to the key derivation function is a randomly generated salt.密钥派生 function 的输入之一是随机生成的盐。 So, the derived key is different each time you run CryptoJS.AES.encrypt
, even with the same inputs, and this is why you're getting a different result every time you run it.因此,每次运行CryptoJS.AES.encrypt
时派生的密钥都是不同的,即使输入相同,这就是为什么每次运行它都会得到不同结果的原因。
See CryptoJS and key/IV length for an example of how to pass a key to CryptoJS.AES.encrypt
instead of a password.有关如何将密钥而不是密码传递给CryptoJS.AES.encrypt
的示例,请参阅CryptoJS 和密钥/IV 长度。 This eliminates the need for the key derivation function, and you'll get the same result every time.这消除了对密钥派生 function 的需要,并且您每次都会得到相同的结果。
var algorithm = 'aes256';
// Encrypt
function Encrypt(word, key) {
var cipher = crypto.createCipher(algorithm, key);
var encrypted = cipher.update(word, 'utf8', 'hex') + cipher.final('hex');
return encrypted;
}
//Decrypt
function Decrypt(word, key) {
var decipher = crypto.createDecipher(algorithm, key);
var decrypted = decipher.update(word, 'hex', 'utf8') +
decipher.final('utf8');
return decrypted;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.