如何使用RSA公钥验证文件

时间:2019-05-09 15:20:27

标签: javascript node.js rsa node-crypto

我的工作基于this answer

我正在尝试使用公共密钥来验证文件。这是我的代码:

var hash = crypto.createHash("sha256");
hash.setEncoding("hex");
var fd = fs.createReadStream("path/to/my/file");
fd.on("end", function() {
    hash.end();
    var fileHash = hash.read();    
    const publicKey = fs.readFileSync('keys/public_key.pem');
    const verifier = crypto.createVerify('RSA-SHA256');
    const testSignature = verifier.verify(publicKey, fileSignature, 'base64');
    console.log("testSignature: \n" + testSignature);
    if (testSignature === fileHash)
        console.log("ok");
    else
        console.log("not ok");
});
fd.pipe(hash);

我不知道此代码是否正确,但是当我在控制台中将其打印时,testSignature等于“ false”。为什么呢

testSignature:
false

加密的哈希(fileSignature变量)是正确的。 base64字符串与我期望的相同。

关于我的代码有什么问题的任何想法吗?谢谢

编辑

以下是生成签名的代码:

var hash = crypto.createHash("sha256");
hash.setEncoding("hex");
var fd = fs.createReadStream("path/to/file");
fd.on("end", function() {
    hash.end();
    var fileHash = hash.read();
    var privateKey = fs.readFileSync('keys/private_key.pem');
    var signer = crypto.createSign('RSA-SHA256');
    signer.update(fileHash);
    fileSignature = signer.sign(privateKey, 'base64');
});
fd.pipe(hash);

1 个答案:

答案 0 :(得分:2)

假设path/to/my/file是您需要验证其内容的文件,则必须将其内容提供给verifier.update()。请尝试以下操作:

const input = fs.readFileSync('path/to/my/file'); // load data contents
const publicKey = fs.readFileSync('keys/public_key.pem').toString(); // load the signature, as a string!
const verifier = crypto.createVerify('RSA-SHA256');
verifier.update(input); // provide data contents to the verifier
const testSignature = verifier.verify(publicKey, fileSignature, 'base64');
console.log("testSignature: \n" + testSignature);

还要确保fileSignature是字符串值而不是Buffer。出于某种原因,我仍在尝试找出原因,如果将Buffer对象传递给verifier.verify,它将无法正常工作:

const fileSignatureBuffer = fs.readFileSync('signature.sha256');
const fileSignatureString = fileSignatureBuffer.toString();
// load public key, create the verifier, provide data contents to verifier, etc.
const testSignature = verifier.verify(publicKey, fileSignatureBuffer); // false
const testSignature = verifier.verify(publicKey, fileSignatureString, 'base64'); // true

编辑: 如果您使用哈希作为签名步骤的输入,则必须在验证步骤中传递相同的哈希。然后代码将如下所示:

const publicKey = fs.readFileSync('keys/public_key.pem').toString(); // load the signature, as a string!
const verifier = crypto.createVerify('RSA-SHA256');
verifier.update(fileSignature); // provide the file signature to the verifier
const testSignature = verifier.verify(publicKey, fileSignature, 'base64');
console.log("testSignature: \n" + testSignature);