Rewrite base64/ArrayBuffer conversion helpers

This rewrites 2 helpers as part of the GitLab Cleanroom project.
parent 27f5e271
...@@ -14,31 +14,36 @@ export function isHTTPS() { ...@@ -14,31 +14,36 @@ export function isHTTPS() {
export const FLOW_AUTHENTICATE = 'authenticate'; export const FLOW_AUTHENTICATE = 'authenticate';
export const FLOW_REGISTER = 'register'; export const FLOW_REGISTER = 'register';
// adapted from https://stackoverflow.com/a/21797381/8204697 /**
function base64ToBuffer(base64) { * Converts a base64 string to an ArrayBuffer
const binaryString = window.atob(base64); *
const len = binaryString.length; * @param {String} str - A base64 encoded string
const bytes = new Uint8Array(len); * @returns {ArrayBuffer}
for (let i = 0; i < len; i += 1) { */
bytes[i] = binaryString.charCodeAt(i); export const base64ToBuffer = (str) => {
} const rawStr = atob(str);
return bytes.buffer; const buffer = new ArrayBuffer(rawStr.length);
} const arr = new Uint8Array(buffer);
for (let i = 0; i < rawStr.length; i += 1) {
// adapted from https://stackoverflow.com/a/9458996/8204697 arr[i] = rawStr.charCodeAt(i);
function bufferToBase64(buffer) {
if (typeof buffer === 'string') {
return buffer;
} }
return arr.buffer;
};
let binary = ''; /**
const bytes = new Uint8Array(buffer); * Converts ArrayBuffer to a base64-encoded string
const len = bytes.byteLength; *
for (let i = 0; i < len; i += 1) { * @param {ArrayBuffer, String} str -
binary += String.fromCharCode(bytes[i]); * @returns {String} - ArrayBuffer to a base64-encoded string.
* When input is a string, returns the input as-is.
*/
export const bufferToBase64 = (input) => {
if (typeof input === 'string') {
return input;
} }
return window.btoa(binary); const arr = new Uint8Array(input);
} return btoa(String.fromCharCode(...arr));
};
/** /**
* Returns a copy of the given object with the id property converted to buffer * Returns a copy of the given object with the id property converted to buffer
......
import { base64ToBuffer, bufferToBase64 } from '~/authentication/webauthn/util';
const encodedString = 'SGVsbG8gd29ybGQh';
const stringBytes = [72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33];
describe('Webauthn utils', () => {
it('base64ToBuffer', () => {
const toArray = (val) => new Uint8Array(val);
expect(base64ToBuffer(encodedString)).toBeInstanceOf(ArrayBuffer);
expect(toArray(base64ToBuffer(encodedString))).toEqual(toArray(stringBytes));
});
it('bufferToBase64', () => {
const buffer = base64ToBuffer(encodedString);
expect(bufferToBase64(buffer)).toBe(encodedString);
});
});
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment