UNPKG

crypto-keygen-suite

Version:

Key generation utilities for cryptographic operations. YES I RENAMED IT OMG BASES AND PROTOCOLS!!! See its folder for all <3

82 lines (70 loc) 2.58 kB
import yargs from 'yargs/yargs'; import { hideBin } from 'yargs/helpers'; import crypto from 'crypto'; // Double Ratchet Key Update Logic (Encryption-Only) class DoubleRatchet { constructor() { this.rootKey = crypto.randomBytes(32); this.chainKey = crypto.randomBytes(32); this.sendingChainKey = this.chainKey; } deriveKeys(chainKey) { const hmac = crypto.createHmac('sha256', chainKey); hmac.update('ratchet key update'); const derivedKeys = hmac.digest(); return { messageKey: derivedKeys.slice(0, 32), nextChainKey: derivedKeys.slice(32), }; } ratchetStep() { this.chainKey = crypto.randomBytes(32); this.sendingChainKey = this.chainKey; console.log("🔄 New ratchet key generated!"); } encryptMessage(message) { if (!this.sendingChainKey) { this.ratchetStep(); } const { messageKey, nextChainKey } = this.deriveKeys(this.sendingChainKey); this.sendingChainKey = nextChainKey; const nonce = crypto.randomBytes(12); const cipher = crypto.createCipheriv('aes-256-gcm', messageKey, nonce); const encrypted = Buffer.concat([cipher.update(message, 'utf8'), cipher.final()]); const authTag = cipher.getAuthTag(); return Buffer.concat([nonce, authTag, encrypted]).toString('hex'); } } // CLI Setup async function main() { const argv = yargs(hideBin(process.argv)) .option('mode', { alias: 'm', type: 'string', choices: ['ratchet', 'encrypt'], describe: 'Trigger a ratchet update or encrypt a message', }) .option('message', { alias: 'msg', type: 'string', describe: 'Message to encrypt', }) .help() .argv; const ratchet = new DoubleRatchet(); if (argv.mode === 'ratchet') { ratchet.ratchetStep(); console.log("🔄 Ratchet key updated!"); } else if (argv.mode === 'encrypt') { if (!argv.message) { console.error("❌ Encryption requires a message!"); return; } const encryptedMessage = ratchet.encryptMessage(argv.message); console.log(`🔐 Encrypted Message (Hex): ${encryptedMessage}`); } else { console.error("❌ Invalid mode. Use --mode ratchet | encrypt"); } } console.log("🚀 Debug: Running main function..."); main();