如何使用 rsa public 密钥验证文件

How to verify file using rsa public key

我的工作基于

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

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);

假设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. For some reason, which I am still trying to figure why, if you pass a Buffer object to 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);