Stw*_*eet 1 javascript node.js node-crypto
想从文件中解密一个字符串。
但是当我在 fs 的字符串上使用 nodejs 解密时,它给出了错误“输入字符串错误”
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));
});
Run Code Online (Sandbox Code Playgroud)
试着做一个像这样的字符串它可以工作
var stringInFile= "encryptedString";
console.log(decrypt(stringInFile));
Run Code Online (Sandbox Code Playgroud)
来自 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"));
Run Code Online (Sandbox Code Playgroud)
例如,这段代码工作得很好,没有错误。
希望能帮助到你。
| 归档时间: |
|
| 查看次数: |
3742 次 |
| 最近记录: |