crypto-keygen-suite
Version:
Key generation utilities for cryptographic operations. YES I RENAMED IT OMG BASES AND PROTOCOLS!!! See its folder for all <3
70 lines (64 loc) • 2.43 kB
JavaScript
import yargs from 'yargs/yargs';
import { hideBin } from 'yargs/helpers';
import crypto from 'crypto';
// Function to generate an ECDH key pair
function generateDHKeys(curve) {
const ecdh = crypto.createECDH(curve);
ecdh.generateKeys();
return {
privateKey: ecdh.getPrivateKey('hex'),
publicKey: ecdh.getPublicKey('hex')
};
}
// Function to compute shared secret
function computeSharedSecret(privateKey, peerPublicKey, curve) {
const ecdh = crypto.createECDH(curve);
ecdh.setPrivateKey(Buffer.from(privateKey, 'hex'));
return ecdh.computeSecret(Buffer.from(peerPublicKey, 'hex'), 'hex');
}
// CLI Setup
async function main() {
const argv = yargs(hideBin(process.argv))
.option('mode', {
alias: 'm',
type: 'string',
choices: ['generate', 'compute'],
describe: 'Choose operation mode: generate keys or compute shared secret',
})
.option('curve', {
alias: 'c',
type: 'string',
default: 'secp256k1',
choices: ['secp256k1', 'prime256v1', 'curve25519'],
describe: 'Select the elliptic curve for DH exchange',
})
.option('privateKey', {
alias: 'p',
type: 'string',
describe: 'Private key for computing shared secret',
})
.option('publicKey', {
alias: 'pub',
type: 'string',
describe: 'Peer public key for computing shared secret',
})
.help()
.argv;
if (argv.mode === 'generate') {
const keys = generateDHKeys(argv.curve);
console.log(`✅ Generated DH Key Pair (Curve: ${argv.curve})`);
console.log(`🔑 Private Key: ${keys.privateKey}`);
console.log(`📡 Public Key: ${keys.publicKey}`);
} else if (argv.mode === 'compute') {
if (!argv.privateKey || !argv.publicKey) {
console.error('Computing shared secret requires both a private key and a peer public key.');
return;
}
const secret = computeSharedSecret(argv.privateKey, argv.publicKey, argv.curve);
console.log(`🔐 Shared Secret (Hex): ${secret}`);
} else {
console.error('Invalid mode. Use --mode generate | compute');
}
}
console.log("🚀 Debug: Running main function...");
main();