简体   繁体   English

node.js加密模块无法加密16个以上字符

[英]node.js crypto module cannot encrypt 16+ characters

I am still rather new to all the terminology around cryptology, so please excuse my ignorance on the subject. 我对密码学的所有术语还算陌生,所以请原谅我对此问题的无知。 I am having something strange happening when using node.js' crypto module. 使用node.js的加密模块时,发生了一些奇怪的事情。 It will encrypt exactly 16 characters only. 它将仅加密16个字符。 Any more and it fails with this error message: 再有,它将失败,并显示以下错误消息:

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)

The code I am using looks like this: 我正在使用的代码如下所示:

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');
}

Why does this not encrypt more than 16 characters? 为什么不加密超过16个字符? Is it because of the algorithm I am using? 是否因为我使用的算法? How can I encrypt something without caring how long it is? 我如何加密某物而不关心它有多长?

The problem is that you're discarding part of your encrypted and decrypted data. 问题是您要丢弃部分加密和解密的数据。 update() can return data just like final() can. update()可以像final()一样返回数据。 So change your encrypt() and decrypt() like: 因此,请像下面这样更改您的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');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM