Skip to content

Instantly share code, notes, and snippets.

@JTRNS
Created September 19, 2023 09:41
Show Gist options
  • Save JTRNS/bf94b489076347b322aa1e40f974243d to your computer and use it in GitHub Desktop.
Save JTRNS/bf94b489076347b322aa1e40f974243d to your computer and use it in GitHub Desktop.
deno random encoded bytes
import {toHashString} from 'https://deno.land/std@0.201.0/crypto/to_hash_string.ts';
import {parse} from 'https://deno.land/std@0.201.0/flags/mod.ts';
const args = parse(Deno.args, {
boolean: ['help'],
alias: {
help: 'h',
encoding: 'e',
},
string: ['encoding'],
default: {
help: false,
encoding: 'hex',
},
});
const help = `
Usage: deno run random.ts [options] number
Options:
--encoding, -e 'hex' | 'base64' Default: hex
Parameters:
number Length of the output in bytes. Default: 32
`;
if (args.help) {
console.log(help);
Deno.exit(0);
}
const [num] = args._;
if (typeof num !== 'number' || isNaN(num) || num < 1 || num % 1 !== 0) {
console.error(`Length must be a positive integer. Got: ${num}`);
Deno.exit(1);
}
console.log(
toHashString(
crypto.getRandomValues(new Uint8Array(num)),
args.encoding as 'hex' | 'base64'
)
);
Deno.exit(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment