CrytoJS AES:加密的字符串被解密为空字符串

时间:2019-06-06 12:29:53

标签: node.js encryption aes cryptojs

我正在修改crypto-js和AES。

我有一段看似简单的代码,它采用一个plainText并使用带有密钥和初始向量的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",

1 个答案:

答案 0 :(得分: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位密钥。

相关问题