diff options
author | timonson <54777088+timonson@users.noreply.github.com> | 2020-10-20 05:08:34 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-10-20 14:08:34 +1100 |
commit | 034ab48086557af00216ffe311c71ad4eb0ec4d5 (patch) | |
tree | 292abc572ed68eb52c1bc773e64f820497e065df /std/jwt/_signature.ts | |
parent | 992c2a436e5fe371807dd43bd293bb811fd529e7 (diff) |
feat(std/jwt): add a JSON Web Token library (#7991)
Co-authored-by: Tim Reichen <timreichen@users.noreply.github.com>
Diffstat (limited to 'std/jwt/_signature.ts')
-rw-r--r-- | std/jwt/_signature.ts | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/std/jwt/_signature.ts b/std/jwt/_signature.ts new file mode 100644 index 000000000..81c1309d1 --- /dev/null +++ b/std/jwt/_signature.ts @@ -0,0 +1,63 @@ +import type { Algorithm } from "./_algorithm.ts"; +import { HmacSha256 } from "../hash/sha256.ts"; +import { HmacSha512 } from "../hash/sha512.ts"; +import { encode as convertUint8ArrayToBase64url } from "../encoding/base64url.ts"; +import { decodeString as convertHexToUint8Array } from "../encoding/hex.ts"; + +export function convertHexToBase64url(input: string): string { + return convertUint8ArrayToBase64url(convertHexToUint8Array(input)); +} + +function encrypt( + algorithm: Algorithm, + key: string, + message: string, +): string { + switch (algorithm) { + case "none": + return ""; + case "HS256": + return new HmacSha256(key).update(message).toString(); + case "HS512": + return new HmacSha512(key).update(message).toString(); + default: + throw new RangeError( + `The algorithm of '${algorithm}' in the header is not supported.`, + ); + } +} + +/** + * Create a signature + * @param algorithm + * @param key + * @param input + */ +export async function create( + algorithm: Algorithm, + key: string, + input: string, +): Promise<string> { + return convertHexToBase64url(await encrypt(algorithm, key, input)); +} + +/** + * Verify a signature + * @param signature + * @param key + * @param alg + * @param signingInput + */ +export async function verify({ + signature, + key, + algorithm, + signingInput, +}: { + signature: string; + key: string; + algorithm: Algorithm; + signingInput: string; +}): Promise<boolean> { + return signature === (await encrypt(algorithm, key, signingInput)); +} |