node.js加密模块不能加密16个以上的字符

时间:2014-10-26 12:51:26

标签: javascript node.js encryption node-crypto

我仍然对密码学的所有术语都很陌生,所以请原谅我对这个问题的无知。使用node.js时,我发生了一些奇怪的事情。加密模块。它只会加密16个字符。任何更多,它失败并显示以下错误消息:

TypeError: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
at Decipher.Cipher.final (crypto.js:292:27)
at decrypt (C:\node_apps\crypto_test\app.js:39:21)
at C:\node_apps\crypto_test\app.js:16:21
at Interface._onLine (readline.js:200:5)
at Interface._line (readline.js:531:8)
at Interface._ttyWrite (readline.js:760:14)
at ReadStream.onkeypress (readline.js:99:10)
at ReadStream.emit (events.js:98:17)
at emitKey (readline.js:1095:12)
at ReadStream.onData (readline.js:840:14)

我使用的代码如下所示:

var rl = require('readline');
var crypto =require('crypto');

var interface = rl.createInterface({
input: process.stdin,
output:process.stdout
});

interface.question('Enter text to encrypt: ',function(texto){
var encrypted = encrypt(texto);
console.log('Encrypted text:',encrypted);

console.log('Decrypting text...');
var decrypted = decrypt(encrypted);
console.log('Decrypted text:',decrypted);
process.exit();
});

function encrypt(text)
{
var cipher =crypto.createCipher('aes192','password');
text = text.toString('utf8');
cipher.update(text);
return cipher.final('binary');

}

function decrypt(text)
{
var decipher = crypto.createDecipher('aes192','password');
decipher.update(text,'binary','utf8');
return decipher.final('utf8');
}

为什么不加密超过16个字符?是因为我使用的算法吗?如何加密某些东西而不关心它有多长时间?

1 个答案:

答案 0 :(得分:1)

问题在于您丢弃了部分加密和解密数据。 update()可以像final()一样返回数据。因此,请更改您的encrypt()decrypt()

function encrypt(text)
{
var cipher =crypto.createCipher('aes192', 'password');
text = text.toString('utf8');
return cipher.update(text, 'utf8', 'binary') + cipher.final('binary');
}

function decrypt(text)
{
var decipher = crypto.createDecipher('aes192', 'password');
return decipher.update(text, 'binary', 'utf8') + decipher.final('utf8');
}