问题描述
我正在使用内置的加密模块,在试图弄清楚为什么 decipher.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,iv);
return { encrypted: Buffer.concat([cipher.update(plainText),cipher.final()]),authTag: cipher.getAuthTag() }
}
decrypt(encrypted,iv,authTag) {
const decipher = crypto.createDecipheriv(algorithm,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,iv);
console.log('encrypted: ',encrypted.toString('hex'));
const decrypted = this.decrypt(encrypted,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,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'));
解密的结果与你加密的明文完全一样!
您可以通过在加密之前在控制台的text
中输出明文,即SignUp()
的内容来轻松验证这一点:
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>
然后解密提供了预期的结果。