为什么我的 decipher.update 返回的是一个函数而不是解密的文本?节点JS

Why is my decipher.update returning a function and not the deciphered text? NodeJS

我正在使用内置的加密模块,并且在试图弄清楚为什么 decipher.update returns 一个函数而不是解密的文本本身时感到沮丧了很多个小时。

代码:

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()]);
}

没有给我解密形式的文本?另外,我怎么能得到它,因为我显然做错了什么。任何帮助都会真的不胜感激。

可能是因为“decrypted.toString('utf-8')”不是在执行函数而是把它变成字符串显示在控制台... 我相信你必须做这样的事情:

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

或但不确定

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

解密后的结果和你加密后的明文完全一样!

您可以在加密之前在控制台的 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>

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