fix: Incorrect usage of ArrayBufferView subarrays #35

This commit is contained in:
microshine 2021-11-10 03:31:25 +03:00
parent 7d6401b210
commit dce231d046
2 changed files with 11 additions and 1 deletions

View File

@ -10,7 +10,7 @@ export class Crypto extends core.Crypto {
if (!ArrayBuffer.isView(array)) { if (!ArrayBuffer.isView(array)) {
throw new TypeError("Failed to execute 'getRandomValues' on 'Crypto': parameter 1 is not of type 'ArrayBufferView'"); throw new TypeError("Failed to execute 'getRandomValues' on 'Crypto': parameter 1 is not of type 'ArrayBufferView'");
} }
const buffer = Buffer.from(array.buffer); const buffer = Buffer.from(array.buffer, array.byteOffset, array.byteLength);
crypto.randomFillSync(buffer); crypto.randomFillSync(buffer);
return array; return array;
} }

View File

@ -23,6 +23,16 @@ context("Crypto", () => {
assert.strictEqual(Buffer.from(array2).equals(array), true); assert.strictEqual(Buffer.from(array2).equals(array), true);
}); });
it("Uint8Array subarray", () => {
const array = new Uint8Array(10);
const subarray = array.subarray(0, 5);
const array2 = crypto.getRandomValues(subarray);
assert.notStrictEqual(Buffer.from(array).toString("hex"), "00000000000000000000");
assert.strictEqual(subarray, array2);
assert.ok(Buffer.from(array).toString("hex").endsWith("0000000000"));
});
it("Uint16Array", () => { it("Uint16Array", () => {
const array = new Uint16Array(5); const array = new Uint16Array(5);
const array2 = crypto.getRandomValues(array); const array2 = crypto.getRandomValues(array);