crypto-keygen-suite
Version:
Key generation utilities for cryptographic operations. YES I RENAMED IT. SIX STATE PROTOCOL!!! See its folder for all <3
90 lines (82 loc) • 2.39 kB
JavaScript
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
function validateKey(key) {
const upperKey = key.toUpperCase();
if (upperKey.length !== 26) return false;
const uniqueLetters = new Set(upperKey);
return uniqueLetters.size === 26;
}
function encrypt(text, key) {
const map = {};
for (let i = 0; i < 26; i++) {
map[alphabet[i]] = key[i].toUpperCase();
}
return [...text].map(char => {
const upper = char.toUpperCase();
if (alphabet.includes(upper)) {
const sub = map[upper];
return char === upper ? sub : sub.toLowerCase();
}
return char;
}).join('');
}
function decrypt(text, key) {
const map = {};
for (let i = 0; i < 26; i++) {
map[key[i].toUpperCase()] = alphabet[i];
}
return [...text].map(char => {
const upper = char.toUpperCase();
if (key.includes(upper)) {
const sub = map[upper];
return char === upper ? sub : sub.toLowerCase();
}
return char;
}).join('');
}
yargs(hideBin(process.argv))
.command('encrypt', 'Encrypt text using substitution cipher', y => {
y.option('key', {
alias: 'k',
describe: '26-letter substitution key',
demandOption: true,
type: 'string'
}).option('text', {
alias: 't',
describe: 'Plaintext to encrypt',
demandOption: true,
type: 'string'
});
}, argv => {
const key = argv.key.toUpperCase();
if (!validateKey(key)) {
console.error('Invalid key. Key must be a 26-letter permutation of the alphabet.');
return;
}
console.log('Encrypted:', encrypt(argv.text, key));
})
.command('decrypt', 'Decrypt text using substitution cipher', y => {
y.option('key', {
alias: 'k',
describe: '26-letter substitution key',
demandOption: true,
type: 'string'
}).option('text', {
alias: 't',
describe: 'Ciphertext to decrypt',
demandOption: true,
type: 'string'
});
}, argv => {
const key = argv.key.toUpperCase();
if (!validateKey(key)) {
console.error('Invalid key. Key must be a 26-letter permutation of the alphabet.');
return;
}
console.log('Decrypted:', decrypt(argv.text, key));
})
.demandCommand()
.strict()
.help()
.argv;