Skip to content

Instantly share code, notes, and snippets.

@s1r-J
Last active October 12, 2023 14:54
Show Gist options
  • Save s1r-J/fdc368b818be78ca58878085c89bd82b to your computer and use it in GitHub Desktop.
Save s1r-J/fdc368b818be78ca58878085c89bd82b to your computer and use it in GitHub Desktop.
function base642ab(base64) {
const str = window.atob(base64);
const len = str.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = str.charCodeAt(i);
}
return bytes.buffer;
}
function ab2base64(ab) {
const str = String.fromCharCode.apply(null, new Uint8Array(ab))
return window.btoa(str);
}
function base64url2ab(base64url) {
return base642ab(base64url2base64(base64url));
}
function ab2base64url(ab) {
const str = String.fromCharCode.apply(null, new Uint8Array(ab))
return base642base64url(window.btoa(str));
}
function base642base64url(base64) {
return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=*$/g, '')
}
function base64url2base64(base64url) {
let base64 = base64url.replace(/-/g, '+').replace(/_/g, '/');
const padding = base64.length % 4;
if (padding > 0) {
return base64 + '===='.slice(padding);
}
return base64;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment