diff options
author | Matthew Miller <matthew@millerti.me> | 2020-06-02 11:51:28 -0700 |
---|---|---|
committer | Matthew Miller <matthew@millerti.me> | 2020-06-02 11:51:28 -0700 |
commit | cac818173050ec1e18d73d0f880c826901cf4abd (patch) | |
tree | fcc2e378c500d933ea710b0b2efc3eea8627ada2 /packages/browser/src/helpers/base64URLStringToBuffer.ts | |
parent | 063282c49fc31570565348a0f1123b3d18a1e4b2 (diff) |
Add new Base64URL<->Buffer helper methods
Diffstat (limited to 'packages/browser/src/helpers/base64URLStringToBuffer.ts')
-rw-r--r-- | packages/browser/src/helpers/base64URLStringToBuffer.ts | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/packages/browser/src/helpers/base64URLStringToBuffer.ts b/packages/browser/src/helpers/base64URLStringToBuffer.ts new file mode 100644 index 0000000..baa258f --- /dev/null +++ b/packages/browser/src/helpers/base64URLStringToBuffer.ts @@ -0,0 +1,33 @@ +/** + * Convert from a Base64URL-encoded string to an Array Buffer. Best used when converting a + * credential ID from a JSON string to an ArrayBuffer, like in allowCredentials or + * excludeCredentials + * + * Helper method to compliment `bufferToBase64URLString` + */ +export default function base64URLStringToBuffer(base64URLString: string): ArrayBuffer { + // Convert from Base64URL to Base64 + const base64 = base64URLString.replace(/-/g, '+').replace(/_/g, '/'); + /** + * Pad with '=' until it's a multiple of four + * (4 - (85 % 4 = 1) = 3) % 4 = 3 padding + * (4 - (86 % 4 = 2) = 2) % 4 = 2 padding + * (4 - (87 % 4 = 3) = 1) % 4 = 1 padding + * (4 - (88 % 4 = 0) = 4) % 4 = 0 padding + */ + const padLength = (4 - (base64.length % 4)) % 4; + const padded = base64.padEnd(base64.length + padLength, '='); + + // Convert to a binary string + const binary = atob(padded); + + // Convert binary string to buffer + const buffer = new ArrayBuffer(binary.length); + const bytes = new Uint8Array(buffer); + + for (let i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i); + } + + return buffer; +} |