Base64 Java Encode and Decode a String

Base64 Java encode and decode a string

You can use following approach:

import org.apache.commons.codec.binary.Base64;

// Encode data on your side using BASE64
byte[] bytesEncoded = Base64.encodeBase64(str.getBytes());
System.out.println("encoded value is " + new String(bytesEncoded));

// Decode data on other side, by processing encoded data
byte[] valueDecoded = Base64.decodeBase64(bytesEncoded);
System.out.println("Decoded value is " + new String(valueDecoded));

Hope this answers your doubt.

Decode Base64 data in Java

As of v6, Java SE ships with JAXB. javax.xml.bind.DatatypeConverter has static methods that make this easy. See parseBase64Binary() and printBase64Binary().

UPDATE: JAXB is no longer shipped with Java (since Java 11). If JAXB is required for your project, you will need to configure the relevant libraries via your dependency management system, for example Maven. If you require the compiler (xjc.exe) you also need to download that separately.

Return decoded String from base64-encoded ByteArrayOutputStream

To find the way back from your Base64 string you need to "inflate" the compressed content like this:

    String base64 = Base64.getEncoder().encodeToString(bArr); // eJzzSM3JyVcozy/KSQEAGKsEPQ==

// reverse
byte[] decodedBytes = Base64.getDecoder().decode(base64);
ByteArrayOutputStream byteArrayOutputStream2 = new ByteArrayOutputStream();
InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(byteArrayOutputStream2);
inflaterOutputStream.write(decodedBytes);
inflaterOutputStream.close();
System.out.println("out: "+ byteArrayOutputStream2.toString()); // Hello World
byteArrayOutputStream2.close();

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

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:

// Sending side
byte[] data = text.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);

// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, "UTF-8");

Or with StandardCharsets:

// Sending side
byte[] data = text.getBytes(StandardCharsets.UTF_8);
String base64 = Base64.encodeToString(data, Base64.DEFAULT);

// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, StandardCharsets.UTF_8);

encode/decode file in java with Base64

You are not closing the files. Also there is the mentioned problem when you use text (String/Reader/Writer) for binary data: corrupt data, slower, double memory, platform dependent when not specifying the encoding.

The optimal solution is not to take the bytes in memory, additionally making a 8/5 larger byte array with base 64.

Use try-with-resources to automatically close the files, even on an exception (like illegal Base 64 chars).

public static void encodeFile(String inputFile, String outputFile)
throws IOException {
Path inPath = Paths.get(inputFile);
Path outPath = Paths.get(outputFile);
try (OutputStream out = Base64.getEncoder().wrap(Files.newOutputStream(outPath))) {
Files.copy(inPath, out);
}
}

public static void decodeFile(String encodedfilecontent, String decodedfile)
throws IOException {
Path inPath = Paths.get(encodedfilecontent);
Path outPath = Paths.get(decodedfile);
try (InputStream in = Base64.getDecoder().wrap(Files.newInputStream(inPath))) {
Files.copy(in, outPath);
}
}

Decoding Base64 String in Java

btoa is broken and shouldn't be used.

The problem is, bytes aren't characters. Base64 encoding does only one thing. It converts bytes to a stream of characters that survive just about any text-based transport mechanism. And Base64 decoding does that one thing in reverse, it converts such characters into bytes.

And the confusion is, you're printing those bytes as if they are characters. They are not.

You end up with the exact same bytes, but javascript and java disagree on how you're supposed to turn that into an ersatz string because you're trying to print it to a console. That's a mistake - bytes aren't characters. Thus, some sort of charset encoding is being used, and you don't want any of this, because these characters clearly aren't intended to be printed like that.

Javascript sort of half-equates characters and bytes and will freely convert one to the other, picking some random encoding. Oof. Javascript sucks in this regard, it is what it is. The MDN docs on btoa explains why you shouldn't use it. You're running into that problem.

Not entirely sure how you fix it in javascript - but perhaps you don't need it. Java is decoding the bytes perfectly well, as is javascript, but javascript then turns those bytes into characters into some silly fashion and that's causing the problem.



Related Topics



Leave a reply



Submit