summaryrefslogtreecommitdiff
path: root/web/js/browser/lib/utils.js
blob: 5bf038335d27f96a2727f354d295415edad73941 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const HEX_STRING = /^(?:[a-fA-F0-9]{2})+$/;
export function hexToUint8(str) {
    if (!HEX_STRING.test(str)) {
        throw new Error(`invalid hex string: ${str}`);
    }
    const bytes = str.match(/[a-fA-F0-9]{2}/g);
    return new Uint8Array(bytes.map((byte) => parseInt(byte, 16)));
}
export function uint8ToHex(array) {
    return array.reduce((str, byte) => str + ('00' + byte.toString(16)).slice(-2), '');
}
export function uint8ToBase64(array) {
    return btoa(String.fromCharCode(...array));
}
export function uint8ToBase64Url(array) {
    return uint8ToBase64(array)
        .replace(/=/g, '')
        .replace(/\+/g, '-')
        .replace(/\//g, '_');
}
export function xor(array1, array2) {
    return new Uint8Array(array1.map((byte, i) => byte ^ array2[i]));
}