Skip to content

Commit 4623321

Browse files
committed
Initial code commit
1 parent a627f58 commit 4623321

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

deps.ts

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
// First party libraries
2+
export { HmacSha256 } from 'https://deno.land/[email protected]/hash/sha256.ts';
3+
export { HmacSha512 } from 'https://deno.land/[email protected]/hash/sha512.ts';
4+
export * as base64url from 'https://deno.land/[email protected]/encoding/base64url.ts';
5+
//export { Sha3_224, Sha3_256, Sha3_384, Sha3_512 } from 'https://deno.land/[email protected]/hash/sha3.ts';
6+

mod.ts

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*!
2+
* keygrip
3+
* Copyright(c) 2011-2014 Jed Schmidt
4+
* Copyright(c) 2020 Christian Norrman
5+
* MIT Licensed
6+
*/
7+
8+
import { HmacSha256, HmacSha512 } from './deps.ts';
9+
10+
const SANITIZE_REGEXP = /\/|\+|=/g;
11+
const SANITIZE_REPLACERS = {
12+
"/": "_",
13+
"+": "-",
14+
"=": "",
15+
} as Record<string, string>;
16+
17+
export enum Algorithm {
18+
SHA256 = 'sha256',
19+
SHA512 = 'sha512',
20+
}
21+
22+
export class Keygrip {
23+
#keys: string[];
24+
#decoder: TextDecoder;
25+
#algo: Algorithm;
26+
27+
constructor(keys: string[], algo: Algorithm=Algorithm.SHA256, enc: string='base64') {
28+
if (!keys || !keys.length) {
29+
throw new Error('Keys must be provided.');
30+
} else if (algo != 'sha256' && algo != 'sha512') {
31+
throw new Error('Algorithm not found');
32+
}
33+
34+
this.#keys = keys;
35+
this.#algo = algo;
36+
this.#decoder = new TextDecoder(enc);
37+
}
38+
39+
sign(data: string, key?: string): string {
40+
let buffer: ArrayBuffer;
41+
key = key ?? this.#keys[0];
42+
43+
if (this.#algo == 'sha256') {
44+
const hash = new HmacSha256(key);
45+
buffer = hash.update(data).arrayBuffer();
46+
} else if (this.#algo == 'sha512') {
47+
const hash = new HmacSha512(key);
48+
buffer = hash.update(data).arrayBuffer();
49+
} else {
50+
// Required for typescript
51+
throw new Error('Algorithm invalid');
52+
}
53+
54+
return this.#decoder
55+
.decode(buffer)
56+
.replace(SANITIZE_REGEXP, s => SANITIZE_REPLACERS[s]);
57+
}
58+
59+
verify(data: string, digest: string): boolean {
60+
return this.index(data, digest) != -1;
61+
}
62+
63+
index(data: string, digest: string): number {
64+
return this.#keys.findIndex(key => digest === this.sign(data, key));
65+
}
66+
}

0 commit comments

Comments
 (0)