UNPKG

crypto-keygen-suite

Version:

Key generation utilities for cryptographic operations. YES I RENAMED IT. SIX STATE PROTOCOL!!! See its folder for all <3

97 lines (83 loc) 2.65 kB
import fs from 'fs'; function calculateCheckDigit(gtin) { const digits = gtin.split('').map(Number); const sum = digits.slice(0, -1).reduce((acc, digit, index) => { // GS1 standard weighting: from right to left, // odd positions = 3, even positions = 1, // your original logic with index % 2 works here return acc + (index % 2 === 0 ? digit : digit * 3); }, 0); return (10 - (sum % 10)) % 10; } const lengths = { 'GTIN8': 7, 'GTIN12': 11, 'GTIN13': 12, 'GTIN14': 13, 'GSIN': 16, 'SSCC': 17, 'GLN': 12, 'GRAI': 13, 'GIAI': 16, 'GSRN': 16, 'GDTI': 16, 'GINC': 17 }; function generateGS1Key(format) { const keyFormat = format.toUpperCase().replace(/-/g, ''); const length = lengths[keyFormat]; if (!length) { throw new Error(`Invalid format '${format}' specified.`); } let key = ''; for (let i = 0; i < length; i++) { key += Math.floor(Math.random() * 10).toString(); } const checkDigit = calculateCheckDigit(key + '0'); return key + checkDigit; } // CLI argument parsing const args = process.argv.slice(2); let format = ''; let count = 1; let outputFile = null; if (args.includes('--help') || args.length === 0) { console.log(` Usage: node gs1gen.js --format <FORMAT> [--count <number>] [--output <file>] Options: --format One of: GTIN-8, GTIN-12, GTIN-13, GTIN-14, GSIN, SSCC, GLN, GRAI, GIAI, GSRN, GDTI, GINC --count Number of keys to generate (default: 1) --output Save generated keys to a file --help Show this help message `); process.exit(0); } // Parse args manually for (let i = 0; i < args.length; i++) { const key = args[i]; const value = args[i + 1]; if (key === '--format') format = value; if (key === '--count') count = parseInt(value) || 1; if (key === '--output') outputFile = value; } if (!format) { console.error('Error: --format is required.'); process.exit(1); } // Generate keys try { const keys = Array.from({ length: count }, () => generateGS1Key(format)); if (outputFile) { const lines = keys.map(key => `${format} key: ${key}`); fs.writeFileSync(outputFile, lines.join('\n'), 'utf-8'); console.log(`Saved ${count} ${format} key(s) to ${outputFile}`); } else { keys.forEach((key, idx) => { console.log(`Generated ${format} [${idx + 1}]: ${key}`); }); } } catch (err) { console.error('Error:', err.message); process.exit(1); }