我正在尝试解密字符串,但测试仍然失败,我似乎无法弄清楚问题。 以下是涉及的文件:
Encryptor.js
import * as crypto from 'crypto'
const hashAlgorithm = 'sha256';
const encryptAlgorithm = 'aes192';
const textEncoding = 'hex';
const encryptionKey = "some secret key";
export const getHash = text => {
try {
const encryptedData = crypto.createHmac(hashAlgorithm, encryptionKey);
encryptedData.setEncoding(textEncoding)
.end(text, () => encryptedData.read())
return encryptedData;
} catch (error) {
console.error(error);
}
}
export const encrypt = text => {
if (!text)
throw Error('Text may not be blank');
try {
const cipher = crypto.createCipher(encryptAlgorithm, encryptionKey);
let cipherText = '';
cipher.on('readable', () => {
let data = cipher.read();
if (data)
cipherText += data.toString(textEncoding);
});
cipher.on('end', () => cipherText);
cipher.write(text);
cipher.end();
}
catch (error) {
return console.error(error);
}
}
export const decrypt = text => {
if (!text)
throw Error('Decrypt: Text may not be blank');
try {
const decipher = crypto.createDecipher(encryptAlgorithm, encryptionKey);
let decrypted = '';
decipher.on('readable', () => {
const data = decipher.read();
if (data)
return decrypted += data.toString('utf8');
});
decipher.on('end', () => decrypted);
decipher.write(text, textEncoding);
decipher.end();
}
catch (error) {
console.error(error);
}
}
Encryptor.test.js
import {getHash, encrypt, decrypt } from './Encryptor.js';
const dataString = "Important information must always be encypted"
it('Should create a hashed message FROM STRING', () => {
expect(getHash(dataString)).not.toEqual(dataString)
})
it('Should encrypt the message FROM STRING', () => {
expect(encrypt(dataString)).not.toEqual(dataString)
})
it('Should decrypt the message FROM ENCRYPTED STRING', () => {
expect(decrypt(encrypt(dataString))).toEqual(dataString)
})
据我了解,这段代码很好。但是,当我运行测试时,最后一个测试失败了:
如果我将文字字符串传递给解密函数,如下所示:
it('Should decrypt the message FROM ENCRYPTED STRING', () => {
expect(decrypt("encypted")).toEqual(dataString)
})
返回的结果为undefined
,我也收到error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
错误
我几乎完全遵循了示例here但没有成功。