UNPKG

crypto-keygen-suite

Version:

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

88 lines (72 loc) 2.35 kB
import crypto from 'crypto'; function rotl32(x, n) { return ((x << n) | (x >>> (32 - n))) >>> 0; } function bufferToWords(buf) { const words = []; for (let i = 0; i < buf.length; i += 4) { words.push(buf.readUInt32LE(i)); } return words; } function wordsToBuffer(words) { const buf = Buffer.alloc(words.length * 4); words.forEach((w, i) => buf.writeUInt32LE(w, i * 4)); return buf; } const S_BOXES = [ [3, 8, 15, 1, 10, 6, 5, 11, 14, 13, 4, 7, 9, 0, 12, 2], [15, 12, 2, 7, 9, 0, 5, 10, 1, 11, 14, 8, 6, 13, 3, 4], [8, 6, 7, 9, 3, 12, 10, 15, 13, 1, 14, 4, 0, 11, 5, 2], [0, 15, 11, 8, 12, 9, 6, 3, 13, 1, 2, 4, 10, 7, 5, 14], [1, 15, 8, 3, 12, 0, 11, 6, 2, 5, 14, 9, 7, 10, 4, 13], [15, 5, 2, 11, 4, 10, 9, 12, 0, 3, 14, 8, 13, 6, 7, 1], [7, 2, 12, 5, 8, 4, 6, 11, 14, 9, 1, 15, 13, 3, 10, 0], [1, 13, 15, 0, 14, 8, 2, 11, 7, 4, 12, 10, 9, 3, 5, 6], ]; function applySBoxToWord(word, sbox) { let result = 0; for (let nibble = 0; nibble < 8; nibble++) { const shift = nibble * 4; const val = (word >>> shift) & 0xF; const sub = S_BOXES[sbox][val]; result |= (sub << shift); } return result >>> 0; } function generateSerpentKey() { return crypto.randomBytes(32); } function keySchedule(keyBuf) { const keyWords = bufferToWords(keyBuf); while (keyWords.length < 8) { keyWords.push(0); } const W = new Uint32Array(132); for (let i = 0; i < 8; i++) { W[i] = keyWords[i]; } for (let i = 8; i < 132; i++) { let temp = W[i-8] ^ W[i-5] ^ W[i-3] ^ W[i-1] ^ 0x9e3779b9 ^ i; W[i] = rotl32(temp, 11); } const roundKeys = []; for (let i = 0; i < 33; i++) { const rkWords = []; for (let j = 0; j < 4; j++) { const word = W[4*i + j]; rkWords.push(applySBoxToWord(word, (32 - i) % 8)); } roundKeys.push(wordsToBuffer(rkWords)); } return roundKeys; } function generateSerpentKeyAndSchedule() { const key = generateSerpentKey(); const roundKeys = keySchedule(key); return { key, roundKeys }; } const result = generateSerpentKeyAndSchedule(); console.log("Generated Serpent Key (HEX):", result.key.toString('hex')); console.log("Round Keys (HEX):"); result.roundKeys.forEach((rk, i) => console.log(`Round ${i}: ${rk.toString('hex')}`));