Skip to content

Commit

Permalink
Implement crypto.subtle.digest() for "sha-1" and "sha-256"
Browse files Browse the repository at this point in the history
  • Loading branch information
TooTallNate committed Jan 18, 2024
1 parent 95d9a3f commit 8510c75
Show file tree
Hide file tree
Showing 6 changed files with 490 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/shiny-lobsters-scream.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'nxjs-runtime': patch
---

Implement `crypto.subtle.digest()` for "sha-1" and "sha-256"
37 changes: 37 additions & 0 deletions apps/tests/src/crypto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { suite } from 'uvu';
import * as assert from 'uvu/assert';

const test = suite('crypto');

function toHex(a: ArrayBuffer) {
const u = new Uint8Array(a);
const s = [];
for (let i = 0; i < u.length; i++) {
s.push(u[i].toString(16).padStart(2, '0'));
}
return s.join('');
}

test('`crypto.getRandomValues()`', () => {
const arr = new Uint8Array(5);
assert.equal(toHex(arr.buffer), '0000000000');
crypto.getRandomValues(arr);
assert.not.equal(toHex(arr.buffer), '0000000000');
});

test("`crypto.subtle.digest('sha-1')`", async () => {
const data = new TextEncoder().encode('hello');
const digest = await crypto.subtle.digest('sha-1', data);
assert.equal(toHex(digest), 'aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d');
});

test("`crypto.subtle.digest('sha-256')`", async () => {
const data = new TextEncoder().encode('hello');
const digest = await crypto.subtle.digest('sha-256', data);
assert.equal(
toHex(digest),
'2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'
);
});

test.run();
1 change: 1 addition & 0 deletions apps/tests/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import './canvas';
import './crypto';
import './error';
import './fetch';
import './form-data';
Expand Down
5 changes: 5 additions & 0 deletions packages/runtime/src/$.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,11 @@ export interface Init {
): number[];

// crypto.c
cryptoDigest(
cb: Callback<ArrayBuffer>,
algorithm: string,
buf: ArrayBuffer
): void;
cryptoRandomBytes(buf: ArrayBuffer, offset: number, length: number): void;

// dns.c
Expand Down
Loading

0 comments on commit 8510c75

Please sign in to comment.