Skip to content

Instantly share code, notes, and snippets.

@vojtechmares
Created February 24, 2023 18:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vojtechmares/457207b9cf25a8b8d53fcb8e64e15f7b to your computer and use it in GitHub Desktop.
Save vojtechmares/457207b9cf25a8b8d53fcb8e64e15f7b to your computer and use it in GitHub Desktop.
Generate cryptographically safe random 32 byte string (AES-256 encryption key), base64 encoded
#!/usr/bin/env deno run
import { encode as base64encode } from 'https://deno.land/std@0.178.0/encoding/base64.ts';
// Generates a random 32 byte encryption key string
function generateEncryptionKey() {
const buf = new Uint8Array(32 / 2); // 32 bytes = 64 hex characters
crypto.getRandomValues(buf);
let result = "";
for (let i = 0; i < buf.length; ++i) {
result += ("0" + buf[i].toString(16)).slice(-2);
}
return result;
}
const key = generateEncryptionKey();
console.log(base64encode(key));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment