节点 JS 加密 "Bad input string"
Node JS crypto "Bad input string"
想要从文件中解密字符串。
但是当我对来自 fs 的字符串使用 nodejs 解密时,它给出了错误 "Bad input string"
var fs = require('fs');
var crypto = require('crypto');
function decrypt(text){
var decipher = crypto.createDecipher('aes-256-ctr', 'password')
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return dec;
}
fs.readFile('./file.json', 'utf8', function (err,data) {
if (err) return console.log(err);
console.log(decrypt(data));
});
试过只制作一个这样的字符串就可以了
var stringInFile= "encryptedString";
console.log(decrypt(stringInFile));
不过
来自 fs 的 console.log(data) 也给出 'encryptedString'
您的代码没有任何问题。问题是您要解密的字符串。您要解密的字符串不能是任何字符串。它必须是从类似 encrypt
函数生成的字符串。
var crypto = require('crypto');
encrypt = function(text, passPhrase){
var cipher = crypto.createCipher('AES-128-CBC-HMAC-SHA1', passPhrase);
var crypted = cipher.update(text,'utf8','hex');
crypted += cipher.final('hex');
return crypted;
}
decrypt = function(text, passPhrase){
var decipher = crypto.createDecipher('AES-128-CBC-HMAC-SHA1', passPhrase)
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return dec;
}
console.log(decrypt(encrypt("Hello", "123"), "123"));
例如,此代码运行良好,没有错误。
希望对您有所帮助。
想要从文件中解密字符串。
但是当我对来自 fs 的字符串使用 nodejs 解密时,它给出了错误 "Bad input string"
var fs = require('fs');
var crypto = require('crypto');
function decrypt(text){
var decipher = crypto.createDecipher('aes-256-ctr', 'password')
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return dec;
}
fs.readFile('./file.json', 'utf8', function (err,data) {
if (err) return console.log(err);
console.log(decrypt(data));
});
试过只制作一个这样的字符串就可以了
var stringInFile= "encryptedString";
console.log(decrypt(stringInFile));
不过 来自 fs 的 console.log(data) 也给出 'encryptedString'
您的代码没有任何问题。问题是您要解密的字符串。您要解密的字符串不能是任何字符串。它必须是从类似 encrypt
函数生成的字符串。
var crypto = require('crypto');
encrypt = function(text, passPhrase){
var cipher = crypto.createCipher('AES-128-CBC-HMAC-SHA1', passPhrase);
var crypted = cipher.update(text,'utf8','hex');
crypted += cipher.final('hex');
return crypted;
}
decrypt = function(text, passPhrase){
var decipher = crypto.createDecipher('AES-128-CBC-HMAC-SHA1', passPhrase)
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return dec;
}
console.log(decrypt(encrypt("Hello", "123"), "123"));
例如,此代码运行良好,没有错误。
希望对您有所帮助。