Decode Base64 data in Java

前端 未结 20 1458
时光说笑
时光说笑 2020-11-21 06:04

I have an image that is Base64 encoded. What is the best way to decode that in Java? Hopefully using only the libraries included with Sun Java 6.

相关标签:
20条回答
  • 2020-11-21 06:37

    As an alternative to sun.misc.BASE64Decoder or non-core libraries, look at javax.mail.internet.MimeUtility.decode().

    public static 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;
    }
    

    Link with full code: Encode/Decode to/from Base64

    0 讨论(0)
  • 2020-11-21 06:38

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

    0 讨论(0)
  • 2020-11-21 06:38

    Hope this helps you:

    import com.sun.org.apache.xml.internal.security.utils.Base64;
    String str="Hello World";
    String base64_str=Base64.encode(str.getBytes("UTF-8"));
    

    Or:

    String str="Hello World";
    String base64_str="";
    try
       {base64_str=(String)Class.forName("java.util.prefs.Base64").getDeclaredMethod("byteArrayToBase64", new Class[]{byte[].class}).invoke(null, new Object[]{str.getBytes("UTF-8")});
       }
    catch (Exception ee) {}
    

    java.util.prefs.Base64 works on local rt.jar,

    But it is not in The JRE Class White List

    and not in Available classes not listed in the GAE/J white-list

    What a pity!

    PS. In android, it's easy because that android.util.Base64 has been included since Android API Level 8.

    0 讨论(0)
  • 2020-11-21 06:39

    My solution is 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);
            }
            return buffer;
        } 
    
    }
    
    0 讨论(0)
  • 2020-11-21 06:40

    This is a late answer, but Joshua Bloch committed his Base64 class (when he was working for Sun, ahem, Oracle) under the java.util.prefs package. This class existed since JDK 1.4.

    E.g.

    String currentString = "Hello World";
    String base64String = java.util.prefs.Base64.byteArrayToBase64(currentString.getBytes("UTF-8"));
    
    0 讨论(0)
  • 2020-11-21 06:41

    Given a test encode/decode example of javax.xml.bind.DatatypeConverter using methods parseBase64Binary() and printBase64Binary() referring to @jeremy-ross and @nightfirecat answer.

    @Test
    public void EncodeDecode() {
        //ENCODE
        String hello = "Hello World";
        byte[] helloBytes = hello.getBytes(StandardCharsets.UTF_8);
        String encodedHello = DatatypeConverter.printBase64Binary(helloBytes);
        LOGGER.info(hello + " encoded=> " + encodedHello);
    
        //DECODE
        byte[] encodedHelloBytes = DatatypeConverter.parseBase64Binary(encodedHello);
        String helloAgain = new String(encodedHelloBytes, StandardCharsets.UTF_8) ;
        LOGGER.info(encodedHello + " decoded=> " + helloAgain);
    
        Assert.assertEquals(hello, helloAgain);
    }
    

    Result:

    INFO - Hello World encoded=> SGVsbG8gV29ybGQ=
    INFO - SGVsbG8gV29ybGQ= decoded=> Hello World
    
    0 讨论(0)
提交回复
热议问题