1 import { arrayToBinaryString, binaryStringToArray, decodeBase64, encodeBase64 } from '@proton/crypto/lib/utils';
3 export const uint8ArrayToString = arrayToBinaryString;
5 export const stringToUint8Array = binaryStringToArray;
7 export const uint8ArrayToBase64String = (array: Uint8Array) => encodeBase64(uint8ArrayToString(array));
9 export const base64StringToUint8Array = (string: string) => stringToUint8Array(decodeBase64(string) || '');
12 * Encode a binary string in the so-called base64 URL (https://tools.ietf.org/html/rfc4648#section-5)
13 * @dev Each character in a binary string can only be one of the characters in a reduced 255 ASCII alphabet. I.e. morally each character is one byte
14 * @dev This function will fail if the argument contains characters which are not in this alphabet
15 * @dev This encoding works by converting groups of three "bytes" into groups of four base64 characters (2 ** 6 ** 4 is also three bytes)
16 * @dev Therefore, if the argument string has a length not divisible by three, the returned string will be padded with one or two '=' characters
18 export const encodeBase64URL = (str: string, removePadding = true) => {
19 const base64String = encodeBase64(str).replace(/\+/g, '-').replace(/\//g, '_');
21 return removePadding ? base64String.replace(/=/g, '') : base64String;
25 * Convert a string encoded in base64 URL into a binary string
28 export const decodeBase64URL = (str: string) => {
29 return decodeBase64((str + '==='.slice((str.length + 3) % 4)).replace(/-/g, '+').replace(/_/g, '/'));
32 export const uint8ArrayToPaddedBase64URLString = (array: Uint8Array) =>
33 encodeBase64URL(uint8ArrayToString(array), false);
35 export const validateBase64string = (str: string, useVariantAlphabet?: boolean) => {
36 const regex = useVariantAlphabet ? /^[-_A-Za-z0-9]*={0,3}$/ : /^[+/A-Za-z0-9]*={0,3}$/;
38 return regex.test(str);
42 * Automatic password reset parameter encoder
44 export const encodeAutomaticResetParams = (json: any) => {
45 const jsonString = JSON.stringify(json);
46 return encodeBase64URL(jsonString);
50 * Automatic password reset parameter decoder
52 export const decodeAutomaticResetParams = (base64String: string) => {
53 const decodedString = decodeBase64URL(base64String);
54 return JSON.parse(decodedString);