Skip to content

Commit

Permalink
Implement non-standard SubtleCrypto timingSafeEqual (cloudflare#542)
Browse files Browse the repository at this point in the history
* Implement timingSafeEqual and test

* Add subtlecrypto extension types

* Use fancy ava methods

Co-authored-by: MrBBot <[email protected]>

---------

Co-authored-by: MrBBot <[email protected]>
  • Loading branch information
DaniFoldi and mrbbot authored Mar 22, 2023
1 parent 1271c80 commit f05a97e
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
3 changes: 2 additions & 1 deletion packages/core/src/standards/crypto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createHash, webcrypto } from "crypto";
import { createHash, timingSafeEqual, webcrypto } from "crypto";
import { WritableStream } from "stream/web";
import { DOMException } from "@miniflare/core";
import { viewToBuffer } from "@miniflare/shared";
Expand Down Expand Up @@ -215,6 +215,7 @@ export function createCrypto(blockGlobalRandom = false): WorkerCrypto {
if (propertyKey === "importKey") return importKey;
if (propertyKey === "exportKey") return exportKey;
if (propertyKey === "sign") return sign;
if (propertyKey === "timingSafeEqual") return timingSafeEqual;
if (propertyKey === "verify") return verify;

let result = Reflect.get(target, propertyKey, receiver);
Expand Down
16 changes: 16 additions & 0 deletions packages/core/test/standards/crypto.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,22 @@ test("crypto: sign/verify: supports other algorithm", async (t) => {
t.true(await crypto.subtle.verify("HMAC", key, signature, data));
});

test("crypto: timingSafeEqual equals", (t) => {
const array1 = new Uint8Array(12);
array1.fill(0, 0);
const array2 = new Uint8Array(12);
array2.fill(0, 0);
t.true(crypto.subtle.timingSafeEqual(array1, array2));
});
test("crypto: timingSafeEqual not equals", (t) => {
const array1 = new Uint8Array(12);
array1.fill(0, 0);
const array2 = new Uint8Array(12);
array2.fill(0, 0);
array2[7] = 1;
t.false(crypto.subtle.timingSafeEqual(array1, array2));
});

// Checking other functions aren't broken by proxy...

test("crypto: gets random values", (t) => {
Expand Down
10 changes: 10 additions & 0 deletions types/crypto.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
declare module "crypto" {
namespace webcrypto {
interface SubtleCrypto {
timingSafeEqual(
a: ArrayBuffer | ArrayBufferView,
b: ArrayBuffer | ArrayBufferView
): boolean;
}
}
}

0 comments on commit f05a97e

Please sign in to comment.