From 1bbae3e505026a953b040f1ab62388d822ba05f0 Mon Sep 17 00:00:00 2001 From: "Visal .In" Date: Thu, 20 Aug 2020 06:52:02 +0700 Subject: [PATCH] Add base64url encoding --- src/utility/encode.ts | 14 ++++++++++++++ tests/rsa/rsa.verify.test.ts | 31 +++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 tests/rsa/rsa.verify.test.ts diff --git a/src/utility/encode.ts b/src/utility/encode.ts index 2241c3d..a97b085 100644 --- a/src/utility/encode.ts +++ b/src/utility/encode.ts @@ -22,6 +22,20 @@ export class encode { return new RawBinary(Uint8Array.from(atob(data), (c) => c.charCodeAt(0))); } + static base64url(data: string) { + let input = data + .replace(/-/g, "+") + .replace(/_/g, "/"); + + const pad = input.length % 4; + if (pad) { + if (pad === 1) throw "Invalid length"; + input += new Array(5 - pad).join("="); + } + + return encode.base64(input); + } + static binary(data: Uint8Array | number[]) { return new RawBinary(data); } diff --git a/tests/rsa/rsa.verify.test.ts b/tests/rsa/rsa.verify.test.ts new file mode 100644 index 0000000..083ee88 --- /dev/null +++ b/tests/rsa/rsa.verify.test.ts @@ -0,0 +1,31 @@ +import { + assertEquals, +} from "https://deno.land/std@0.63.0/testing/asserts.ts"; +import { RSA, encode } from "./../../mod.ts"; + +Deno.test("Verify RSASSA-PKSC1-v1_5", async () => { + const publicKey = `-----BEGIN PUBLIC KEY----- + MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnzyis1ZjfNB0bBgKFMSv + vkTtwlvBsaJq7S5wA+kzeVOVpVWwkWdVha4s38XM/pa/yr47av7+z3VTmvDRyAHc + aT92whREFpLv9cj5lTeJSibyr/Mrm/YtjCZVWgaOYIhwrXwKLqPr/11inWsAkfIy + tvHWTxZYEcXLgAXFuUuaS3uF9gEiNQwzGTU1v0FqkqTBr4B8nW3HCN47XUu0t8Y0 + e+lf4s4OxQawWD79J9/5d3Ry0vbV3Am1FtGJiJvOwRsIfVChDpYStTcHTCMqtvWb + V6L11BWkpzGXSW4Hv43qa+GSYOD2QU68Mb59oSk2OB+BtOLpJofmbGEGgvmwyCI9 + MwIDAQAB + -----END PUBLIC KEY-----`; + + const key = RSA.parseKey(publicKey); + const rsa = new RSA(key); + let base64 = + "POstGetfAytaZS82wHcjoTyoqhMyxXiWdR7Nn7A29DNSl0EiXLdwJ6xC6AfgZWF1bOsS_TuYI3OG85AmiExREkrS6tDfTQ2B3WXlrr-wp5AokiRbz3_" + + "oB4OxG-W9KcEEbDRcZc0nH3L7LzYptiy1PtAylQGxHTWZXtGz4ht0bAecBgmpdgXMguEIcoqPJ1n3pIWk_dUZegpqx0Lka21H6XxUTxiy8OcaarA8zdn" + + "PUnV6AmNP3ecFawIFYdvJB_cm-GvpCSbr8G8y_Mllj8f4x9nBH8pQux89_6gUY618iYv7tuPWBFfEbLxtF2pZS6YC1aSfLQxeNe8djT9YjpvRZA"; + + const verified = await rsa.verify( + encode.base64url(base64), + "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0", + { algorithm: "rsassa-pkcs1-v1_5", hash: "sha256" }, + ); + + assertEquals(verified, true); +});