const crypto = require('crypto');
const fs = require('fs');
// Generate a key pair for this example
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
// Message to sign and verify
const message = 'This is a message to be verified';
// Create a signature for the example
const sign = crypto.createSign('SHA256');
sign.update(message);
const signature = sign.sign(privateKey, 'hex');
// Create a Verify object
const verify = crypto.createVerify('SHA256');
// Update with the message
verify.update(message);
// Verify the signature with the public key
const isValid = verify.verify(publicKey, signature, 'hex');
console.log('Message:', message);
console.log('Signature:', signature.substring(0, 32) + '...');
console.log('Is signature valid?', isValid);
// Try to verify with a tampered message
const tamperedVerify = crypto.createVerify('SHA256');
tamperedVerify.update(message + ' (tampered)');
const isTamperedValid = tamperedVerify.verify(publicKey, signature, 'hex');
console.log('Is tampered signature valid?', isTamperedValid);