I'm trying to cut over a C# tool into Javascript that requires an API key to be converted to Base64 byte array. I'm developing this in Postman to give us a little API test bed.
In C# the function
"21ZgNVIEm7LUY95FbBHK6bYYHrbKAaZcqTKSpU+jC3MViAZvKcTqIN6sZYMSUsDuPLONCYw57bpbZe/paMWeqg=="
and returns the following using the 'FromBase64String' function in one step.
"219 86 96 53 82 4 155 178 212 99 222 69 108 17 202 233 182 24 30 182 202 1 166 92 169 50 146 165 79 163 11 115 21 136 6 111 41 196 234 32 222 172 101 131 18 82 192 238 60 179 141 9 140 57 237 186 91 101 239 233 104 197 158 170"
I've been searching for a JavaScript equivalent and have tried the CryptoJS library using the 'CryptoJS.enc.Base64.parse' function but it just returns the hex string not the byte array. ie
'db56603552049bb2d463de456c11cae9b6181eb6ca01a65ca93292a54fa30b731588066f29c4ea20deac65831252c0ee3cb38d098c39edba5b65efe968c59eaa'
Is there a way to get the output formatted as a Byte Array?
thanks in advance
1 Answer 1
Literally the first hit for me on two different search engines when searching for "javascript from base64": MDN - Base64 encoding and decoding. Which points you at atob
. atob
returns a string (because it predates Uint8Array
). You can easily convert from the string to a Uint8Array
, though, through Uint8Array.from
, if using the string isn't convenient:
const str = "21ZgNVIEm7LUY95FbBHK6bYYHrbKAaZcqTKSpU+jC3MViAZvKcTqIN6sZYMSUsDuPLONCYw57bpbZe/paMWeqg==";
const data = atob(str);
const array = Uint8Array.from(data, b => b.charCodeAt(0));
console.log(array);