Skip to content
Advertisement

Does anyone know how to decode and encode a string in Base64 using Base64?

I am using the following code, but it’s not working.

JavaScript

Advertisement

Answer

First:

  • Choose an encoding. UTF-8 is generally a good choice; stick to an encoding which will definitely be valid on both sides. It would be rare to use something other than UTF-8 or UTF-16.

Transmitting end:

  • Encode the string to bytes (e.g. text.getBytes(encodingName))
  • Encode the bytes to base64 using the Base64 class
  • Transmit the base64

Receiving end:

  • Receive the base64
  • Decode the base64 to bytes using the Base64 class
  • Decode the bytes to a string (e.g. new String(bytes, encodingName))

So something like:

JavaScript

Or with StandardCharsets:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement