const crypto = require('crypto');
// Generate key pairs for different algorithms
function generateRSAKeyPair() {
return crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
}
function generateECKeyPair() {
return crypto.generateKeyPairSync('ec', {
namedCurve: 'prime256v1',
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'sec1',
format: 'pem'
}
});
}
// Generate different key pairs
const rsaKeys = generateRSAKeyPair();
const ecKeys = generateECKeyPair();
// Message to sign and verify
const message = 'Message to verify with different algorithms';
// Function to sign and verify with a specific algorithm
function testSignatureVerification(algorithm, privateKey, publicKey, message) {
try {
// Sign the message
const sign = crypto.createSign(algorithm);
sign.update(message);
const signature = sign.sign(privateKey, 'hex');
// Verify the signature
const verify = crypto.createVerify(algorithm);
verify.update(message);
const isValid = verify.verify(publicKey, signature, 'hex');
// Try to verify with a tampered message
const tamperedVerify = crypto.createVerify(algorithm);
tamperedVerify.update(message + ' (tampered)');
const isTamperedValid = tamperedVerify.verify(publicKey, signature, 'hex');
return {
algorithm,
signatureLength: signature.length / 2, // Convert hex to bytes
isValid,
isTamperedValid
};
} catch (error) {
return {
algorithm,
error: error.message
};
}
}
// Test various signature algorithms
console.log(`Message: "${message}"`);
console.log('-----------------------------------------------');
// RSA signatures with different hash algorithms
const rsaAlgorithms = ['RSA-SHA256', 'RSA-SHA384', 'RSA-SHA512'];
rsaAlgorithms.forEach(algo => {
const result = testSignatureVerification(algo, rsaKeys.privateKey, rsaKeys.publicKey, message);
console.log(`${algo}:`);
console.log(` Signature length: ${result.signatureLength} bytes`);
console.log(` Is valid: ${result.isValid}`);
console.log(` Is tampered valid: ${result.isTamperedValid}\n`);
});
// ECDSA signatures with different hash algorithms
const ecdsaAlgorithms = ['SHA256', 'SHA384', 'SHA512'].map(hash => ({
algo: `ecdsa-with-${hash}`,
key: ecKeys.privateKey,
pubKey: ecKeys.publicKey
}));
ecdsaAlgorithms.forEach(({algo, key, pubKey}) => {
const result = testSignatureVerification(algo, key, pubKey, message);
console.log(`${algo}:`);
if (result.error) {
console.log(` Error: ${result.error}\n`);
} else {
console.log(` Signature length: ${result.signatureLength} bytes`);
console.log(` Is valid: ${result.isValid}`);
console.log(` Is tampered valid: ${result.isTamperedValid}\n`);
}
});