Commit 6674e1ca authored by Olena Horal-Koretska's avatar Olena Horal-Koretska

Merge branch 'cleanroom-base64-arraybuffer-conversion-helpers' into 'master'

Rewrite base64/ArrayBuffer conversion helpers

See merge request gitlab-org/gitlab!79739
parents 678b00bf f7ebadc3
......@@ -14,31 +14,36 @@ export function isHTTPS() {
export const FLOW_AUTHENTICATE = 'authenticate';
export const FLOW_REGISTER = 'register';
// adapted from https://stackoverflow.com/a/21797381/8204697
function base64ToBuffer(base64) {
const binaryString = window.atob(base64);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i += 1) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
// adapted from https://stackoverflow.com/a/9458996/8204697
function bufferToBase64(buffer) {
if (typeof buffer === 'string') {
return buffer;
/**
* Converts a base64 string to an ArrayBuffer
*
* @param {String} str - A base64 encoded string
* @returns {ArrayBuffer}
*/
export const base64ToBuffer = (str) => {
const rawStr = atob(str);
const buffer = new ArrayBuffer(rawStr.length);
const arr = new Uint8Array(buffer);
for (let i = 0; i < rawStr.length; i += 1) {
arr[i] = rawStr.charCodeAt(i);
}
return arr.buffer;
};
let binary = '';
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i += 1) {
binary += String.fromCharCode(bytes[i]);
/**
* Converts ArrayBuffer to a base64-encoded string
*
* @param {ArrayBuffer, String} str -
* @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
......
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