const crypto = require('crypto');
// Generate a keypair for this example
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
// Create a Sign object and update with multiple pieces of data
const sign = crypto.createSign('SHA256');
sign.update('First part of the message. ');
sign.update('Second part of the message. ');
sign.update('Third part of the message.');
// Create the signature
const signature = sign.sign(privateKey, 'hex');
console.log('Verifying message created with multiple updates:');
// Create a Verify object and update with the same data
const verify = crypto.createVerify('SHA256');
verify.update('First part of the message. ');
verify.update('Second part of the message. ');
verify.update('Third part of the message.');
// Verify the signature
const isValid = verify.verify(publicKey, signature, 'hex');
console.log('Is signature valid?', isValid);
// Try with different order of updates (should fail)
const wrongOrderVerify = crypto.createVerify('SHA256');
wrongOrderVerify.update('Second part of the message. ');
wrongOrderVerify.update('First part of the message. ');
wrongOrderVerify.update('Third part of the message.');
const isWrongOrderValid = wrongOrderVerify.verify(publicKey, signature, 'hex');
console.log('Is wrong order valid?', isWrongOrderValid);
// Try with all data in one update (should work)
const singleUpdateVerify = crypto.createVerify('SHA256');
singleUpdateVerify.update('First part of the message. Second part of the message. Third part of the message.');
const isSingleUpdateValid = singleUpdateVerify.verify(publicKey, signature, 'hex');
console.log('Is single update valid?', isSingleUpdateValid);