b64.ts 906 B

1234567891011121314151617181920212223242526272829303132
  1. export function decodeB64StringToArrayBuffer(input: string): ArrayBuffer {
  2. const bytes = Math.floor((input.length / 4) * 3)
  3. const ab = new ArrayBuffer(bytes)
  4. const uarray = new Uint8Array(ab)
  5. const keyStr =
  6. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
  7. let chr1, chr2, chr3
  8. let enc1, enc2, enc3, enc4
  9. let j = 0
  10. input = input.replace(/[^A-Za-z0-9+/=]/g, "")
  11. for (let i = 0; i < bytes; i += 3) {
  12. // get the 3 octets in 4 ASCII chars
  13. enc1 = keyStr.indexOf(input.charAt(j++))
  14. enc2 = keyStr.indexOf(input.charAt(j++))
  15. enc3 = keyStr.indexOf(input.charAt(j++))
  16. enc4 = keyStr.indexOf(input.charAt(j++))
  17. chr1 = (enc1 << 2) | (enc2 >> 4)
  18. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2)
  19. chr3 = ((enc3 & 3) << 6) | enc4
  20. uarray[i] = chr1
  21. if (enc3 !== 64) uarray[i + 1] = chr2
  22. if (enc4 !== 64) uarray[i + 2] = chr3
  23. }
  24. return ab
  25. }