为什么我的decrypt.update返回的是一个函数,而不是解密的文本?NodeJS



我正在使用内置的加密模块,在试图弄清楚为什么decrypt.update返回一个函数而不是解密文本本身时,我感到沮丧了好几个小时。

代码:

const file = path.join(__dirname, '../secret.txt');
const fileIV = path.join(__dirname, '../iv.txt');
const at = path.join(__dirname, '../at.txt')
var secret = fs.readFileSync(file, 'utf-8');
const algorithm = 'aes-256-gcm';
var text = 'default'
var encrypted = secret;
const iv = crypto.randomBytes(16);
encrypt(plainText, key, iv) {
const cipher = crypto.createCipheriv(algorithm, key, iv);
return { encrypted: Buffer.concat([cipher.update(plainText), cipher.final()]), authTag: cipher.getAuthTag() }
}
decrypt(encrypted, key, iv, authTag) {
const decipher = crypto.createDecipheriv(algorithm, key, iv).setAuthTag(authTag);
console.log('this worked decrypt');
return Buffer.concat([decipher.update(encrypted), decipher.final()]);
}
SignUp(pass)
{
console.log(pass);
var pair = ec.genKeyPair(); 
text = pair.getPrivate.toString('hex');
const key = crypto.scryptSync(pass, 'baethrowssalt', 32);
console.log(`The key is:${key}`); 
const {encrypted, authTag} = this.encrypt(text, key, iv);
console.log('encrypted: ',encrypted.toString('hex'));
const decrypted = this.decrypt(encrypted, key, iv, authTag);
console.log('Decrypted:', decrypted.toString('utf-8'));
return console.log(`Close and reopen your app to integrate your wallet securely`); 
}

在控制台中,当我打印出我最初尝试用scrypt:加密的私钥的解密结果时,它会打印出这个

Decrypted: function getPrivate(enc) {
if (enc === 'hex')
return this.priv.toString(16, 2);
else
return this.priv;
}

为什么

decrypt(encrypted, key, iv, authTag) {
const decipher = crypto.createDecipheriv(algorithm, key, iv).setAuthTag(authTag);
console.log('this worked decrypt');
return Buffer.concat([decipher.update(encrypted), decipher.final()]);
}

没有给我文本的解密形式?此外,既然我显然做错了什么,我该如何获得它。任何帮助都将不胜感激。

解密的结果与您加密的明文完全相同!

在加密之前,您可以在控制台的SignUp()中输出明文,即text的内容,从而轻松验证这一点:

var text = pair.getPrivate.toString('hex');             
console.log('Initial plaintext:', text);    // Initial plaintext: function getPrivate(enc) {...

text意外内容的原因是您只是忘记了getPrivate后面的括号对,它应该是:

var text = pair.getPrivate().toString('hex'); 
console.log('Initial plaintext:', text);    // Initial plaintext: <the hex encoded private key>

然后解密提供了预期的结果。

这可能是因为"解密.toString('utf-8'(";不是执行函数,而是将其转换为字符串以在控制台中显示。。。我相信你必须做这样的事情:

let decryptedResult = decrypted.toString('utf-8'); console.log('Decrypted:', decryptedResult.toString('utf-8'));

或者但不确定

console.log('Decrypted:', (decrypted).toString('utf-8'));

相关内容

  • 没有找到相关文章

最新更新