I base my work on this answer
I'm trying to verify a file using a public key. Here is my code:
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);
I don't know if this code is correct, but testSignature
is equal to "false" when i printed it in the console. Why ?
testSignature:
false
The encrypted hash (the fileSignature
variable) is correct. The base64 string is the same as I expect.
Any idea about what is wrong in my code ? Thanks
EDIT
Here is the code that generates the signature:
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);