This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Debug Note < Implement Base64 data decoding in Java >

Ask questions

I have a Base64 encoded image. What is the best way to decode in Java? You want to use only the libraries that come with Sun Java 6.

Answer a:

Starting with V6, Java SE comes with JAXB. Javax.mail. XML. Bind. DatatypeConverter has a static method can simplify the process. See parseBase64Binary() and printBase64Binary().

Answer two:

Since Java 8, there have been officially supported apis for Base64 encoding and decoding. Over time, it may become the default choice. The API includes the class java.util.base64 and its nested classes.

It supports three different types: basic, URL-safe, and MIME.

Example code using “basic” encoding:

import java.util.Base64;

byte[] bytes = "Hello, World!".getBytes("UTF-8");
String encoded = Base64.getEncoder().encodeToString(bytes);
byte[] decoded = Base64.getDecoder().decode(encoded);
Copy the code

Java.util.base64 includes more methods for configuring encoders and decoders and using different classes as inputs and outputs (byte arrays, strings, ByteBuffers, java.io streams).

Answer three:

No utilities needed -Sun ships with Java’s Base64 encoder.

You can import like this:

import sun.misc.BASE64Decoder;
Copy the code

Then use it like this:

BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(encodedBytes);
Copy the code

Answer 4:

My solution is the fastest and easiest.

public class MyBase64 {

    private final static char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();

    private static int[]  toInt   = new int[128];

    static {
        for(int i=0; i< ALPHABET.length; i++){ toInt[ALPHABET[i]]= i; }}/**
     * Translates the specified byte array into Base64 string.
     *
     * @param buf the byte array (not null)
     * @return the translated Base64 string (not null)
     */
    public static String encode(byte[] buf){
        int size = buf.length;
        char[] ar = new char[((size + 2) / 3) * 4];
        int a = 0;
        int i=0;
        while(i < size){
            byte b0 = buf[i++];
            byte b1 = (i < size) ? buf[i++] : 0;
            byte b2 = (i < size) ? buf[i++] : 0;

            int mask = 0x3F;
            ar[a++] = ALPHABET[(b0 >> 2) & mask];
            ar[a++] = ALPHABET[((b0 << 4) | ((b1 & 0xFF) > >4)) & mask];
            ar[a++] = ALPHABET[((b1 << 2) | ((b2 & 0xFF) > >6)) & mask];
            ar[a++] = ALPHABET[b2 & mask];
        }
        switch(size % 3) {case 1: ar[--a]  = '=';
            case 2: ar[--a]  = '=';
        }
        return new String(ar);
    }

    /**
     * Translates the specified Base64 string into a byte array.
     *
     * @param s the Base64 string (not null)
     * @return the byte array (not null)
     */
    public static byte[] decode(String s){
        int delta = s.endsWith( "= =")?2 : s.endsWith( "=")?1 : 0;
        byte[] buffer = new byte[s.length()*3/4 - delta];
        int mask = 0xFF;
        int index = 0;
        for(int i=0; i< s.length(); i+=4){
            int c0 = toInt[s.charAt( i )];
            int c1 = toInt[s.charAt( i + 1)];
            buffer[index++]= (byte)(((c0 << 2) | (c1 >> 4)) & mask);
            if(index >= buffer.length){
                return buffer;
            }
            int c2 = toInt[s.charAt( i + 2)];
            buffer[index++]= (byte)(((c1 << 4) | (c2 >> 2)) & mask);
            if(index >= buffer.length){
                return buffer;
            }
            int c3 = toInt[s.charAt( i + 3 )];
            buffer[index++]= (byte)(((c2 << 6) | c3) & mask);
        }
        returnbuffer; }}Copy the code

Answer 5:

See sun.misc.BASE64Decoder as an alternative or non-core library

Javax.mail. Mail. Internet. MimeUtility. Decode (). publicstatic byte[] encode(byte[] b) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    OutputStream b64os = MimeUtility.encode(baos, "base64");
    b64os.write(b);
    b64os.close();
    return baos.toByteArray();
}
public static byte[] decode(byte[] b) throws Exception {
    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    InputStream b64is = MimeUtility.decode(bais, "base64");
    byte[] tmp = new byte[b.length];
    int n = b64is.read(tmp);
    byte[] res = new byte[n];
    System.arraycopy(tmp, 0, res, 0, n);
    return res;
}
Copy the code

The complete code links: www.rgagnon.com/javadetails…

The article translated from Stack Overflow: stackoverflow.com/questions/4…