Why Convert Base64 to ArrayBuffer?
If you are building a secure application using the Web Crypto API, you will immediately run into a data formatting problem. Native cryptographic functions like crypto.subtle.encrypt() strictly require data to be passed as a BufferSource (typically an ArrayBuffer or Uint8Array).
However, you cannot easily store raw binary ArrayBuffers in a PostgreSQL database, transmit them inside JSON payloads, or append them to URL fragments. To transport ciphertext across the internet, you must encode the raw binary into a Base64 String. This tool helps developers test their encoding and decoding logic visually.
How to convert Base64 to Uint8Array in JavaScript
You cannot use the standard `TextEncoder` for this. You must decode the Base64 string into binary characters, and then map those characters into a typed array. Here is the vanilla JavaScript approach:
function base64ToArrayBuffer(base64) {
const binaryString = window.atob(base64);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
How to convert ArrayBuffer to Base64
Conversely, once the Web Crypto API encrypts your payload, it outputs an ArrayBuffer. Convert that buffer back into a Base64 string before sending your POST request:
function arrayBufferToBase64(buffer) {
let binary = '';
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}