const crypto = require('crypto');
// Message to sign
const message = 'Message to sign with different key formats';
// Function to sign with different key formats
function signWithKey(privateKey, keyFormat) {
try {
const sign = crypto.createSign('SHA256');
sign.update(message);
return {
format: keyFormat,
signature: sign.sign(privateKey, 'hex')
};
} catch (error) {
return {
format: keyFormat,
error: error.message
};
}
}
// Generate a new RSA key pair
const { privateKey: pemPrivateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
console.log(`Message: "${message}"`);
// 1. Sign with PEM-encoded private key (string)
console.log('\n1. PEM-encoded private key (string):');
console.log(signWithKey(pemPrivateKey, 'PEM string'));
// 2. Sign with PEM-encoded private key (buffer)
console.log('\n2. PEM-encoded private key (buffer):');
console.log(signWithKey(Buffer.from(pemPrivateKey), 'PEM buffer'));
// 3. Sign with KeyObject
console.log('\n3. KeyObject:');
const keyObject = crypto.createPrivateKey(pemPrivateKey);
console.log(signWithKey(keyObject, 'KeyObject'));
// 4. Sign with PassThrough crypto engine (if available)
try {
// Note: This might not be available in all Node.js versions/configurations
console.log('\n4. Private key with engine:');
const engineKey = {
key: pemPrivateKey,
padding: crypto.constants.RSA_PKCS1_PADDING
};
console.log(signWithKey(engineKey, 'Key with options'));
} catch (error) {
console.log('\n4. Private key with engine:');
console.log({ format: 'Key with options', error: error.message });
}
// 5. Sign with JSON Web Key (JWK)
// Note: This requires conversion, as Node.js doesn't directly support JWK for sign
console.log('\n5. JWK (requires conversion):');
try {
// This is a simplified example - actual JWK handling would be more complex
const pemToJwk = require('pem-jwk').pem2jwk; // You would need to install this package
const jwk = pemToJwk(pemPrivateKey);
console.log({ format: 'JWK', note: 'JWK needs to be converted to PEM or KeyObject first' });
} catch (error) {
console.log({ format: 'JWK', note: 'Example requires pem-jwk package' });
}