Uint8Array to Base64 in Workers

I am using some of the web crypto “techniques” to encrypt data I send to the client… so I can store it in a cache and use it on subsequent requests. And for added security.

I have my encrypted data… but it’s an ArrayBuffer… Uint8Array.

I’m struggling to convert it to base64 so I can send it back to the client.

I looked at the example for creating signed Requests in the Workers docs… and this is the code that caught my eye…

const base64Mac = btoa(String.fromCharCode(...new Uint8Array(mac)));

When I tried this in my browser… it would not work. My code was nearly identical.

const base64Data = btoa(String.fromCharCode(...encryptedData)

But it would not let me spread the Array Buffer.

Any helps or ideas on doing this?

Recently needed something similar, got this from SubtleCrypto docs on MDN, works for my case (hex-encoding), should be easy to modify for yours

const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');

What would be the reason you want to encode/decode to base64 when caching/serving the content?

Are you aware that you can directly send a ArrayBuffer to a writable. You can also write an ArrayBuffer to the Workers KV Store API and Workers Cache API.