Skip to content

Instantly share code, notes, and snippets.

@0xVikasRushi
Created June 16, 2024 12:07
Show Gist options
  • Save 0xVikasRushi/9b29b379f6fb411ab95d6e7b6daa5f0b to your computer and use it in GitHub Desktop.
Save 0xVikasRushi/9b29b379f6fb411ab95d6e7b6daa5f0b to your computer and use it in GitHub Desktop.
export class Base64DecoderUtils {
constructor() {
this.haveU8 = typeof Uint8Array === "function";
this.decoder = undefined;
}
decode(a) {
let isString = typeof a === "string";
let i;
if (this.decoder === undefined) {
let b64 =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
ignore = "= \f\n\r\t\u00A0\u2028\u2029";
this.decoder = [];
for (i = 0; i < 64; ++i) this.decoder[b64.charCodeAt(i)] = i;
for (i = 0; i < ignore.length; ++i)
this.decoder[ignore.charCodeAt(i)] = -1;
this.decoder["-".charCodeAt(0)] = this.decoder["+".charCodeAt(0)];
this.decoder["_".charCodeAt(0)] = this.decoder["/".charCodeAt(0)];
}
let out = this.haveU8 ? new Uint8Array((a.length * 3) >> 2) : [];
let bits = 0,
char_count = 0,
len = 0;
for (i = 0; i < a.length; ++i) {
let c = isString ? a.charCodeAt(i) : a[i];
if (c === 61) break; // '='.charCodeAt(0)
c = this.decoder[c];
if (c === -1) continue;
if (c === undefined) throw "Illegal character at offset " + i;
bits |= c;
if (++char_count >= 4) {
out[len++] = bits >> 16;
out[len++] = (bits >> 8) & 0xff;
out[len++] = bits & 0xff;
bits = 0;
char_count = 0;
} else {
bits <<= 6;
}
}
switch (char_count) {
case 1:
throw "Base64 encoding incomplete: at least 2 bits missing";
case 2:
out[len++] = bits >> 10;
break;
case 3:
out[len++] = bits >> 16;
out[len++] = (bits >> 8) & 0xff;
break;
}
if (this.haveU8 && out.length > len) out = out.subarray(0, len); // in case it was originally longer because of ignored characters
return out;
}
}
export class Base64 {
static re =
/-----BEGIN [^-]+-----([A-Za-z0-9+/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+/=\s]+)====|^([A-Za-z0-9+/=\s]+)$/;
static decode(a) {
let m = Base64.re.exec(a);
if (m) {
if (m[1]) a = m[1];
else if (m[2]) a = m[2];
else if (m[3]) a = m[3];
else throw "RegExp out of sync";
}
return new Base64DecoderUtils().decode(a);
}
}
export function parseCertificate(input) {
const Base64CertRegex =
/-----BEGIN [^-]+-----([A-Za-z0-9+/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+/=\s]+)====|^([A-Za-z0-9+/=\s]+)$/;
const matches = input.match(Base64CertRegex);
if (!matches) {
return null;
}
const [_, encoded1, encoded2, encoded3] = matches;
const encoded = encoded1 || encoded2 || encoded3;
return encoded.trim();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment