MIRROR: javascript for 馃悳's, a tiny runtime with big ambitions
1import { test, summary } from './helpers.js';
2
3console.log('Crypto Tests\n');
4
5test('crypto exists', typeof crypto, 'object');
6test('crypto toStringTag', Object.prototype.toString.call(crypto), '[object Crypto]');
7
8const rand1 = crypto.random();
9const rand2 = crypto.random();
10test('random returns number', typeof rand1, 'number');
11test('random returns positive', rand1 >= 0, true);
12test('random returns different values', rand1 !== rand2, true);
13
14const bytes = crypto.randomBytes(16);
15test('randomBytes returns object', typeof bytes, 'object');
16test('randomBytes length', bytes.length, 16);
17test('randomBytes values are numbers', typeof bytes[0], 'number');
18test('randomBytes values in range', bytes[0] >= 0 && bytes[0] <= 255, true);
19
20const uuid1 = crypto.randomUUID();
21const uuid2 = crypto.randomUUID();
22test('randomUUID returns string', typeof uuid1, 'string');
23test('randomUUID length', uuid1.length, 36);
24test('randomUUID format', /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(uuid1), true);
25test('randomUUID unique', uuid1 !== uuid2, true);
26
27const uuidv7_1 = crypto.randomUUIDv7();
28const uuidv7_2 = crypto.randomUUIDv7();
29test('randomUUIDv7 returns string', typeof uuidv7_1, 'string');
30test('randomUUIDv7 length', uuidv7_1.length, 36);
31test('randomUUIDv7 version 7', uuidv7_1[14], '7');
32test('randomUUIDv7 unique', uuidv7_1 !== uuidv7_2, true);
33test('randomUUIDv7 monotonic', uuidv7_1 < uuidv7_2, true);
34
35const arr = new Uint8Array(8);
36const result = crypto.getRandomValues(arr);
37test('getRandomValues returns same array', result === arr, true);
38test(
39 'getRandomValues fills array',
40 Array.from(arr).some(v => v !== 0),
41 true
42);
43
44const arr32 = new Uint32Array(4);
45crypto.getRandomValues(arr32);
46test(
47 'getRandomValues works with Uint32Array',
48 Array.from(arr32).some(v => v !== 0),
49 true
50);
51
52summary();