|
| 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