Skip to content Skip to sidebar Skip to footer

How To Verify File Using Rsa Public Key

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.createRe

Solution 1:

Assuming path/to/my/file is the file of which contents you need to verify, you have to provide its contents to verifier.update(). Try the following:

const input = fs.readFileSync('path/to/my/file'); // load data contentsconst 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 verifierconst testSignature = verifier.verify(publicKey, fileSignature, 'base64');
console.log("testSignature: \n" + testSignature);

Also, make sure that fileSignature is a string value and not a Buffer. For some reason, which I am still trying to figure why, if you pass a Buffer object to verifier.verify it will not work:

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); // falseconst testSignature = verifier.verify(publicKey, fileSignatureString, 'base64'); // true

EDIT: If you are using a hash as input to the signing step, then you have to pass the same hash in the verify step. Then code would look as follows:

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 verifierconst testSignature = verifier.verify(publicKey, fileSignature, 'base64');
console.log("testSignature: \n" + testSignature);

Post a Comment for "How To Verify File Using Rsa Public Key"