2020-08-25 10:05:51 -07:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const common = require('../common');
|
|
|
|
|
|
|
|
if (!common.hasCrypto)
|
|
|
|
common.skip('missing crypto');
|
|
|
|
|
|
|
|
const { Buffer } = require('buffer');
|
|
|
|
const assert = require('assert');
|
2022-12-16 20:55:42 +01:00
|
|
|
const { crypto } = globalThis;
|
2020-08-25 10:05:51 -07:00
|
|
|
|
2021-07-19 13:55:53 +02:00
|
|
|
[
|
|
|
|
undefined, null, '', 1, {}, [],
|
|
|
|
new Float32Array(1),
|
|
|
|
new Float64Array(1),
|
2022-01-12 00:49:56 +08:00
|
|
|
new DataView(new ArrayBuffer(1)),
|
2021-07-19 13:55:53 +02:00
|
|
|
].forEach((i) => {
|
|
|
|
assert.throws(
|
2022-12-16 20:55:42 +01:00
|
|
|
() => crypto.getRandomValues(i),
|
2021-07-19 13:55:53 +02:00
|
|
|
{ name: 'TypeMismatchError', code: 17 },
|
|
|
|
);
|
2020-08-25 10:05:51 -07:00
|
|
|
});
|
|
|
|
|
|
|
|
{
|
|
|
|
const buf = new Uint8Array(0);
|
2022-12-16 20:55:42 +01:00
|
|
|
crypto.getRandomValues(buf);
|
2020-08-25 10:05:51 -07:00
|
|
|
}
|
|
|
|
|
2021-07-19 13:55:53 +02:00
|
|
|
const intTypedConstructors = [
|
|
|
|
Int8Array,
|
|
|
|
Int16Array,
|
|
|
|
Int32Array,
|
|
|
|
Uint8Array,
|
|
|
|
Uint16Array,
|
|
|
|
Uint32Array,
|
2022-01-12 00:49:56 +08:00
|
|
|
Uint8ClampedArray,
|
2021-07-19 13:55:53 +02:00
|
|
|
BigInt64Array,
|
|
|
|
BigUint64Array,
|
|
|
|
];
|
2020-08-25 10:05:51 -07:00
|
|
|
|
2021-07-19 13:55:53 +02:00
|
|
|
for (const ctor of intTypedConstructors) {
|
|
|
|
const buf = new ctor(10);
|
|
|
|
const before = Buffer.from(buf.buffer).toString('hex');
|
2022-12-16 20:55:42 +01:00
|
|
|
crypto.getRandomValues(buf);
|
2021-07-19 13:55:53 +02:00
|
|
|
const after = Buffer.from(buf.buffer).toString('hex');
|
2020-08-25 10:05:51 -07:00
|
|
|
assert.notStrictEqual(before, after);
|
|
|
|
}
|
|
|
|
|
|
|
|
{
|
2022-06-29 13:50:40 +08:00
|
|
|
const buf = Buffer.alloc(10);
|
|
|
|
const before = buf.toString('hex');
|
2022-12-16 20:55:42 +01:00
|
|
|
crypto.getRandomValues(buf);
|
2022-06-29 13:50:40 +08:00
|
|
|
const after = buf.toString('hex');
|
2020-08-25 10:05:51 -07:00
|
|
|
assert.notStrictEqual(before, after);
|
|
|
|
}
|
|
|
|
|
|
|
|
{
|
|
|
|
let kData;
|
|
|
|
try {
|
|
|
|
kData = Buffer.alloc(65536 + 1);
|
|
|
|
} catch {
|
|
|
|
// Ignore if error here.
|
|
|
|
}
|
|
|
|
|
|
|
|
if (kData !== undefined) {
|
2022-06-29 14:08:22 +08:00
|
|
|
assert.throws(
|
2022-12-16 20:55:42 +01:00
|
|
|
() => crypto.getRandomValues(kData),
|
2022-06-29 14:08:22 +08:00
|
|
|
{ name: 'QuotaExceededError', code: 22 },
|
|
|
|
);
|
2020-08-25 10:05:51 -07:00
|
|
|
}
|
|
|
|
}
|
2023-05-13 18:40:42 +10:00
|
|
|
|
|
|
|
{
|
|
|
|
const typedArray = new Uint8Array(32);
|
|
|
|
assert.strictEqual(crypto.getRandomValues(typedArray), typedArray);
|
|
|
|
}
|