CrytoJS AES: зашифрованная строка расшифровывается в пустую строку - PullRequest
0 голосов
/ 06 июня 2019

Я возился с 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 ""

Может кто-нибудь объяснить, что происходит?Я видел немало примеров по Интернету, и все они, кажется, работают нормально.Но здесь текст не расшифровывается.

PS : Я использую версию "crypto-js": "^3.1.9-1",

1 Ответ

1 голос
/ 06 июня 2019

Может быть, попробуйте немного изменить ваш код, это работает для меня.

Как указано в комментариях, я считаю, что проблема с вашим первоначальным примером была длиной ключа.

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-битный ключ.

...