Skip to content

Instantly share code, notes, and snippets.

@kek-Sec
Created November 14, 2020 17:48
Show Gist options
  • Save kek-Sec/724aa6024bd76adddba94134e6d711eb to your computer and use it in GitHub Desktop.
Save kek-Sec/724aa6024bd76adddba94134e6d711eb to your computer and use it in GitHub Desktop.
Typescript base64 to ascii String
export class base64decode{
private PADCHAR: string = '=';
private ALPHA: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
private getByte(s: string, i: number): number {
const x = s.charCodeAt(i);
return x;
}
private getByte64(s: string, i: number): number {
const idx = this.ALPHA.indexOf(s.charAt(i));
return idx;
}
public decode (s: string): string {
let pads = 0,
i, b10, imax = s.length,
x = [];
s = String(s);
if (imax === 0) {
return s;
}
if (s.charAt(imax - 1) === this.PADCHAR) {
pads = 1;
if (s.charAt(imax - 2) === this.PADCHAR) {
pads = 2;
}
imax -= 4;
}
for (i = 0; i < imax; i += 4) {
b10 = (this.getByte64(s, i) << 18) | (this.getByte64(s, i + 1) << 12) | (this.getByte64(s, i + 2) << 6) | this.getByte64(s, i + 3);
x.push(String.fromCharCode(b10 >> 16, (b10 >> 8) & 255, b10 & 255));
}
switch (pads) {
case 1:
b10 = (this.getByte64(s, i) << 18) | (this.getByte64(s, i + 1) << 12) | (this.getByte64(s, i + 2) << 6);
x.push(String.fromCharCode(b10 >> 16, (b10 >> 8) & 255));
break;
case 2:
b10 = (this.getByte64(s, i) << 18) | (this.getByte64(s, i + 1) << 12);
x.push(String.fromCharCode(b10 >> 16));
break;
}
return x.join('');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment