-
Notifications
You must be signed in to change notification settings - Fork 2
/
test.ts
45 lines (40 loc) · 1.2 KB
/
test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { test, runIfMain } from "https://deno.land/x/testing/mod.ts";
import { assertEquals } from "https://deno.land/x/testing/asserts.ts";
import { sha1 } from "./mod.ts";
interface TestVector {
msg: Uint8Array;
msg_bit_len: number;
hash: Uint8Array;
}
/** Deserializes a Uint8Array from a hexadecimal string. */
function hex2buf(hex: string): Uint8Array {
const len: number = hex.length;
if (len % 2 || !/^[0-9a-fA-F]*$/.test(hex)) {
throw new TypeError("Invalid hex string.");
}
hex = hex.toLowerCase();
const buf: Uint8Array = new Uint8Array(Math.floor(len / 2));
const end: number = len / 2;
for (let i: number = 0; i < end; ++i) {
buf[i] = parseInt(hex.substr(i * 2, 2), 16);
}
return buf;
}
const testVectors: TestVector[] = JSON.parse(
new TextDecoder().decode(Deno.readFileSync("./test_vectors.json"))
).map(
({ msg, msg_bit_len, hash }): TestVector => ({
msg: hex2buf(msg),
msg_bit_len,
hash: hex2buf(hash)
})
);
testVectors.forEach(({ msg, msg_bit_len, hash }: TestVector) => {
test({
name: `SHA1 ${msg_bit_len ? msg_bit_len / 8 : 0}-byte msg`,
fn(): void {
assertEquals(sha1(msg), hash);
}
});
});
runIfMain(import.meta, { parallel: true });