AES128 uses a 16 byte secret key.
const key = new Uint8Array(16);
crypto.getRandomValues(key);| function random(): number { | |
| const buffer = new ArrayBuffer(8); | |
| const bytes = crypto.getRandomValues(new Uint8Array(buffer)); | |
| // sets the exponent value (11 bits) to 01111111111 (1023) | |
| // since the bias is 1023 (2 * (11 - 1) - 1), 1023 - 1023 = 0 | |
| // 2^0 * (1 + [52 bit number between 0-1]) = number between 1-2 | |
| bytes[0] = 63; | |
| bytes[1] = bytes[1] | 240; | |
| function generateRandomInteger(max: number): number { | |
| if (max < 0 || !Number.isInteger(max)) { | |
| throw new Error("Argument 'max' must be an integer greater than or equal to 0") | |
| } | |
| const bitLength = (max - 1).toString(2).length | |
| const shift = bitLength % 8 | |
| const bytes = new Uint8Array(Math.ceil(bitLength / 8)) | |
| while (true) { | |
| crypto.getRandomValues(bytes) | |
| // This zeroes bits that can be ignored to increase the chance `result` < `max`. |