CryptoJS AES:加密字符串被解密为空字符串

CrytoJS AES: Encrypted string gets decrypted to empty string

我正在修补 crypto-js 和 AES。

我有一段看似简单的代码,它采用纯文本并使用带有密钥和初始向量的 AES 对其进行加密。

当我尝试解密加密文本时,由于某种原因它被解密为空字符串。

这是片段:

const { enc, AES } = require("crypto-js");

const KEY = enc.Utf8.parse("this is a key");
const IV = enc.Utf8.parse("this is initial vector");

const originalText = "someone@example.com";

const hash = AES.encrypt(originalText, KEY, { iv: IV });
const hashText = hash.toString();

console.log(`"${originalText}" was encrypted to "${hashText}"`);

const hashTextCopy = `${hashText}`;
const decrypt = AES.decrypt(hashTextCopy, KEY, { iv: IV });
const decryptText = decrypt.toString(enc.Utf8);

console.log(`"${hashTextCopy}" was decrypted to "${decryptText}"`);

我得到的输出是:

"someone@example.com" was encrypted to "IgyDXGNVD8IokknoZqjamG0QecGvBM/dyxx4il8gCHA="
"IgyDXGNVD8IokknoZqjamG0QecGvBM/dyxx4il8gCHA=" was decrypted to ""

谁能解释一下这是怎么回事?我已经在 Internet 上看到了很多这样的例子,它们似乎都工作得很好。但是在这里,文本没有被解密。

PS: 我使用的版本是"crypto-js": "^3.1.9-1",

也许尝试稍微更改您的代码,这对我有用。

如评论中所述,我认为您最初示例的问题在于密钥长度。

const { enc, AES } = require("crypto-js");

// Keep as a string..
const KEY = "this is a key";
const IV = enc.Utf8.parse("this is initial vector");

const originalText = "someone@example.com";

const hash = AES.encrypt(originalText, KEY, { iv: IV });
const hashText = hash.toString();

console.log(`"${originalText}" was encrypted to "${hashText}"`);

const hashTextCopy = `${hashText}`;
const decrypt = AES.decrypt(hashTextCopy, KEY, { iv: IV });
const decryptText = decrypt.toString(enc.Utf8);

console.log(`"${hashTextCopy}" was decrypted to "${decryptText}"`);

这也有效:

const { enc, AES } = require("crypto-js");

// 128-bit key works nicely
const KEY = enc.Hex.parse("000102030405060708090a0b0c0d0e0f");
const IV = enc.Utf8.parse("this is initial vector");

const originalText = "someone@example.com";

const hash = AES.encrypt(originalText, KEY, { iv: IV });
const hashText = hash.toString();

console.log(`"${originalText}" was encrypted to "${hashText}"`);

const hashTextCopy = `${hashText}`;
const decrypt = AES.decrypt(hashTextCopy, KEY, { iv: IV });
const decryptText = decrypt.toString(enc.Utf8);

console.log(`"${hashTextCopy}" was decrypted to "${decryptText}"`);

关键:

const KEY = enc.Utf8.parse("abcdfghi");

也能正常工作(因为它是 128 位)。 256 也行。

const KEY = enc.Utf8.parse("abcdfghijklmnopq");

如果您只使用密码短语,将从中生成一个 256 位密钥。