const crypto = require('crypto');
// Message to sign
const message = 'Message for DSA and ECDSA signatures';
// Generate ECDSA key pair
function generateECKeyPair(curveName = 'prime256v1') {
return crypto.generateKeyPairSync('ec', {
namedCurve: curveName,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'sec1', // or 'pkcs8'
format: 'pem'
}
});
}
// Function to sign and verify with a specific algorithm and key pair
function testSignatureAlgorithm(algorithm, keyType, keyPair, message) {
try {
// Sign the message
const sign = crypto.createSign(algorithm);
sign.update(message);
const signature = sign.sign(keyPair.privateKey, 'hex');
// Verify the signature
const verify = crypto.createVerify(algorithm);
verify.update(message);
const isValid = verify.verify(keyPair.publicKey, signature, 'hex');
return {
algorithm: `${keyType}-${algorithm}`,
signatureLength: signature.length / 2, // Convert hex to bytes
isValid
};
} catch (error) {
return {
algorithm: `${keyType}-${algorithm}`,
error: error.message
};
}
}
// Test ECDSA with different curves
const curves = ['prime256v1', 'secp384r1', 'secp521r1'];
console.log(`Message: "${message}"`);
console.log('\nECDSA Signatures:');
curves.forEach(curve => {
const ecKeyPair = generateECKeyPair(curve);
// Test with different hash algorithms
const hashAlgos = ['SHA256', 'SHA384', 'SHA512'];
hashAlgos.forEach(hashAlgo => {
const result = testSignatureAlgorithm(hashAlgo, `ECDSA-${curve}`, ecKeyPair, message);
console.log(result);
});
});
// Test EdDSA if available
try {
console.log('\nEdDSA Signatures:');
// Ed25519
const ed25519KeyPair = crypto.generateKeyPairSync('ed25519', {
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
// Sign with Ed25519
const sign = crypto.createSign('SHA512'); // Hash algorithm is ignored for Ed25519
sign.update(message);
const signature = sign.sign(ed25519KeyPair.privateKey, 'hex');
// Verify with Ed25519
const verify = crypto.createVerify('SHA512');
verify.update(message);
const isValid = verify.verify(ed25519KeyPair.publicKey, signature, 'hex');
console.log({
algorithm: 'Ed25519',
signatureLength: signature.length / 2,
isValid
});
} catch (error) {
console.log({
algorithm: 'Ed25519',
error: error.message
});
}