diff --git a/src/crypto.ts b/src/crypto.ts index 2b558b3..513d9a3 100644 --- a/src/crypto.ts +++ b/src/crypto.ts @@ -10,7 +10,7 @@ export class Crypto extends core.Crypto { if (!ArrayBuffer.isView(array)) { 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); return array; } diff --git a/test/crypto.ts b/test/crypto.ts index 2f48d68..93b1280 100644 --- a/test/crypto.ts +++ b/test/crypto.ts @@ -23,6 +23,16 @@ context("Crypto", () => { 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", () => { const array = new Uint16Array(5); const array2 = crypto.getRandomValues(array);