crypto-keygen-suite
Version:
Key generation utilities for cryptographic operations. YES I RENAMED IT. SIX STATE PROTOCOL!!! See its folder for all <3
133 lines (119 loc) • 3.18 kB
JavaScript
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
function uid(length) {
const HEX = Array.from({ length: 36 }, (_, i) => i.toString(36)).join('');
let result = '';
for (let i = 0; i < (length || 11); i++) {
result += HEX[Math.floor(Math.random() * 36)];
}
return result;
}
const xptagPrefix = () => uid(9);
const xptagPrivate = (t, a) => xptag(t, a, true);
function xptag(t, a, r) {
const e = a || uid(9);
const i = uid(16);
let x = r ? 3 : 1;
let o = '';
if (t) {
let a;
if (x | 4) {
x |= 4;
}
if (t < 0) {
x |= 8;
a = Math.ceil(-t / 5);
} else {
a = Math.ceil(Date.now() / 1000 / 60 / 5) + Math.ceil(t / 5);
}
o = a.toString(16);
}
return e + i + x.toString(16) + o;
}
function xptagDecode(tag) {
if (typeof tag !== 'string' || tag.length < 26) {
throw new Error('Invalid xptag string');
}
const prefix = tag.slice(0, 9);
const id = tag.slice(9, 25);
const flagHex = tag.slice(25, 26);
const flags = parseInt(flagHex, 16);
const timestampHex = tag.slice(26);
let timestamp = null;
let timestampReadable = null;
const isPrivate = (flags & 0x3) === 3;
const bit4Set = (flags & 0x4) !== 0;
const bit8Set = (flags & 0x8) !== 0;
if (timestampHex) {
const timeValue = parseInt(timestampHex, 16);
if (!isNaN(timeValue)) {
if (bit8Set) {
timestamp = -timeValue * 5;
timestampReadable = `Negative offset: ${timestamp} (units of 5 minutes)`;
} else {
timestamp = timeValue * 5 * 60 * 1000;
timestampReadable = new Date(timestamp).toISOString();
}
}
}
return {
prefix,
id,
flags,
isPrivate,
bit4Set,
bit8Set,
timestampHex: timestampHex || null,
timestamp,
timestampReadable,
};
}
// CLI using yargs
yargs(hideBin(process.argv))
.scriptName('xptag-cli')
.usage('$0 <cmd> [args]')
.command(
'generate',
'Generate a new xptag',
(y) =>
y
.option('time', {
alias: 't',
describe: 'Time offset in minutes (positive or negative)',
type: 'number',
default: 0,
})
.option('private', {
alias: 'p',
describe: 'Generate a private xptag',
type: 'boolean',
default: false,
}),
(argv) => {
let offset = argv.time;
if (offset !== 0) offset = Math.ceil(offset / 5) * 5; // normalize to 5 min units
const tag = xptag(offset, undefined, argv.private);
console.log(tag);
}
)
.command(
'decode <tag>',
'Decode an xptag string',
(y) =>
y.positional('tag', {
describe: 'xptag string to decode',
type: 'string',
}),
(argv) => {
try {
const decoded = xptagDecode(argv.tag);
console.log(JSON.stringify(decoded, null, 2));
} catch (e) {
console.error('Error:', e.message);
}
}
)
.demandCommand(1, 'You need to specify a command')
.help()
.parse();