当前位置:  开发笔记 > 编程语言 > 正文

用Java解码Base64数据

如何解决《用Java解码Base64数据》经验,为你挑选了11个好方法。

我有一个Base64编码的图像.在Java中解码它的最佳方法是什么?希望仅使用Sun Java 6附带的库.



1> Jeremy Ross..:

从v6开始,Java SE附带了JAXB.javax.xml.bind.DatatypeConverter有静态的方法,使这很容易.见parseBase64Binary()printBase64Binary().


但是,似乎`printBase64Binary(..)`方法不执行Base64的MIME版本(http://en.wikipedia.org/wiki/Base64#MIME),而私有Sun和Commons实现使用这个.特别是,对于大于76个字符的String,添加换行符.我没有找到如何为此行为配置JAXB的实现...... :-(
警告!parseBase64Binary将以静默方式跳过无效字符,并且不会检查base64的有效性.最好使用Commons Codec或Guava Base64.请注意,Guava拒绝换行符和空白字符,因此您需要解析省略空格的字符串:BaseEncoding.base64().decode(s.replaceAll("\\ s",""))
小心.此函数不适用于长度超过65000的数据.(java版本1.6)
但是,sun实现将忽略换行符.所以他们是兼容的.
不要使用它,因为你会在jdk 9中遇到问题:java.lang.NoClassDefFoundError(javax/xml/bind/DatatypeConverter)

2> Andrea..:

Java 8开始,有一个官方支持的Base64编码和解码API.这可能会成为默认选择.

API包括类java.util.Base64及其嵌套类.它支持三种不同的风格:基本,URL安全和MIME.

使用"基本"编码的示例代码:

import java.util.Base64;

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

该文档java.util.Base64包括几种配置编码器和解码器的方法,以及使用不同的类作为输入和输出(字节数组,字符串,ByteBuffers,java.io流).


Java 7是EOLed,Java 9即将到来,这对我来说是对的!
@JohnMerlino如果不需要与旧Java版本的兼容性,我建议使用此API,因为JRE具有比大多数库更强的兼容性策略.此外,它包含在JRE中,它不会以任何可能的方式约束您的依赖项.
我知道这是一个古老的讨论,但是从今天开始,这应该是公认的答案:)

3> MattK..:

不需要使用commons - Sun发布带有Java的base64编码器.你可以这样导入它:

import sun.misc.BASE64Decoder;

然后像这样使用它:

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

encodedBytesa java.lang.String或a 在哪里java.io.InputStream?请注意,sun.*Sun不会"正式支持" 这些课程.

编辑:谁知道这将是我发布的最有争议的答案?我知道sun.*包不支持或保证不会继续存在,而且我确实知道Commons并且一直使用它.然而,海报要求提供一个"包含在Sun Java 6中"的课程,这就是我想要回答的问题.我同意Commons是最好的方式.

编辑2:正如amir75指出的那样,Java 6+附带JAXB,其中包含支持编码/解码Base64的代码.请参阅下面的Jeremy Ross的回答.


-1 - 这是内部Sun代码,不是J2SE的一部分(它不可移植),并且可能随时消失 - Sun明确表示不在用户代码中使用其内部库
是的,因此我的免责声明在最后.
Bzzt.在专业环境中,使用不受支持的未记录的功能永远不是正确的决定.在企业环境中,"实验"成为"生产代码",没有机会修复黑客攻击.
在一个研究部门,该代码被标记为实验,当它被标记时总是被废弃,这是正确的决定.
这是一个短期项目,只是一个实验,不想经历新库的批准过程.所以这是这个问题的正确答案.
@Ryan P:虽然这个答案在您的情况下可能是最适合您的(一次性实验性研究代码),因此这个答案对您来说是正确的,但您的问题并未明确表明您处于非生产阶段上下文...这个答案可能会误导那些没有阅读所有评论的人.最好用你的约束来澄清你的问题,这样它们就更明显了.就目前而言,您的问题是"在Java中解码[base64]的最佳方法是什么?" - 并使用sun.misc.BASE64Decoder不是那个一般问题的正确答案.
sun.misc.BASE64Decoder已经与JRE一起发货至少1.1.为什么sun不把它(和BASE64Encoder)放在java.util包中?
Java6 +用户应该向下滚动到下面的JAXB答案.不需要太阳专用课程:)
@Jason:你不是第一个有这个想法的人,它已经提交了11(!!)年前:http://bugs.sun.com/bugdatabase/view_bug.do?video_id = 4235519
同样也向我致敬.使用内部Sun代码是个坏主意.
是的,这是短期权宜之计和长期可维护性之间的折腾.它包含在Java 6中,这是海报所询问的内容,尽管它可能会在后来的Java 6版本中消失.如果发生这种情况,我同意Commons应该用于它的位置.

4> Yuval Adam..:

特别是在Commons Codec中:class Base64to decode(byte[] array)orencode(byte[] array)


您可以将文本'Commons Codec'链接到项目页面.那样这个答案会比Kevin的好:)
@LiHaoyi问题是Sun的JDK附带的库,其中不包括Commons的任何内容.

5> jontro..:

Guava现在内置了Base64解码功能.

使用BaseEncoding.base64().decode()

至于在输入使用中处理可能的空格

BaseEncoding.base64().decode(CharMatcher.WHITESPACE.removeFrom(...));

有关更多信息,请参阅此讨论



6> GeorgeK..:

我的解决方案是最快速,最简单的.

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

}


它不是马车! - 读取javadoc注释... decode(..)的参数是*base64*String不仅仅是任何String.`byte [] b1 = {1,2,3}; byte [] b2 = decode(encode(b1)); System.out.println(Arrays.equals(b1,b2));`// => true
为什么最快?你有任何基准吗?
最快最容易?重新发明轮子 ?!
我运行了一些测试,将这个类与commons-codec进行比较,似乎工作正常.我需要这样简单的东西,因为我只需要base64编码,并且不需要commons-codec提供的所有额外的东西,谢谢.
这信任吗?如果您不想导入外部库,这似乎是最简单的.

7> RealHowTo..:

作为替代sun.misc.BASE64Decoder或非核心库,请查看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;
}

链接完整代码:对Base64进行编码/解码


javax.mail不是核心的一部分.

8> aleroot..:

这是我自己的实现,如果它对某人有用:

public class Base64Coder {

    // The line separator string of the operating system.
    private static final String systemLineSeparator = System.getProperty("line.separator");

    // Mapping table from 6-bit nibbles to Base64 characters.
    private static final char[] map1 = new char[64];
       static {
          int i=0;
          for (char c='A'; c<='Z'; c++) map1[i++] = c;
          for (char c='a'; c<='z'; c++) map1[i++] = c;
          for (char c='0'; c<='9'; c++) map1[i++] = c;
          map1[i++] = '+'; map1[i++] = '/'; }

    // Mapping table from Base64 characters to 6-bit nibbles.
    private static final byte[] map2 = new byte[128];
       static {
          for (int i=0; isun.misc.BASE64Encoder.encodeBuffer(byte[]).
    * @param in  An array containing the data bytes to be encoded.
    * @return    A String containing the Base64 encoded data, broken into lines.
    */
    public static String encodeLines (byte[] in) {
       return encodeLines(in, 0, in.length, 76, systemLineSeparator); }

    /**
    * Encodes a byte array into Base 64 format and breaks the output into lines.
    * @param in            An array containing the data bytes to be encoded.
    * @param iOff          Offset of the first byte in in to be processed.
    * @param iLen          Number of bytes to be processed in in, starting at iOff.
    * @param lineLen       Line length for the output data. Should be a multiple of 4.
    * @param lineSeparator The line separator to be used to separate the output lines.
    * @return              A String containing the Base64 encoded data, broken into lines.
    */
    public static String encodeLines (byte[] in, int iOff, int iLen, int lineLen, String lineSeparator) {
       int blockLen = (lineLen*3) / 4;
       if (blockLen <= 0) throw new IllegalArgumentException();
       int lines = (iLen+blockLen-1) / blockLen;
       int bufLen = ((iLen+2)/3)*4 + lines*lineSeparator.length();
       StringBuilder buf = new StringBuilder(bufLen);
       int ip = 0;
       while (ip < iLen) {
          int l = Math.min(iLen-ip, blockLen);
          buf.append (encode(in, iOff+ip, l));
          buf.append (lineSeparator);
          ip += l; }
       return buf.toString(); }

    /**
    * Encodes a byte array into Base64 format.
    * No blanks or line breaks are inserted in the output.
    * @param in  An array containing the data bytes to be encoded.
    * @return    A character array containing the Base64 encoded data.
    */
    public static char[] encode (byte[] in) {
       return encode(in, 0, in.length); }

    /**
    * Encodes a byte array into Base64 format.
    * No blanks or line breaks are inserted in the output.
    * @param in    An array containing the data bytes to be encoded.
    * @param iLen  Number of bytes to process in in.
    * @return      A character array containing the Base64 encoded data.
    */
    public static char[] encode (byte[] in, int iLen) {
       return encode(in, 0, iLen); }

    /**
    * Encodes a byte array into Base64 format.
    * No blanks or line breaks are inserted in the output.
    * @param in    An array containing the data bytes to be encoded.
    * @param iOff  Offset of the first byte in in to be processed.
    * @param iLen  Number of bytes to process in in, starting at iOff.
    * @return      A character array containing the Base64 encoded data.
    */
    public static char[] encode (byte[] in, int iOff, int iLen) {
       int oDataLen = (iLen*4+2)/3;       // output length without padding
       int oLen = ((iLen+2)/3)*4;         // output length including padding
       char[] out = new char[oLen];
       int ip = iOff;
       int iEnd = iOff + iLen;
       int op = 0;
       while (ip < iEnd) {
          int i0 = in[ip++] & 0xff;
          int i1 = ip < iEnd ? in[ip++] & 0xff : 0;
          int i2 = ip < iEnd ? in[ip++] & 0xff : 0;
          int o0 = i0 >>> 2;
          int o1 = ((i0 &   3) << 4) | (i1 >>> 4);
          int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
          int o3 = i2 & 0x3F;
          out[op++] = map1[o0];
          out[op++] = map1[o1];
          out[op] = op < oDataLen ? map1[o2] : '='; op++;
          out[op] = op < oDataLen ? map1[o3] : '='; op++; }
       return out; }

    /**
    * Decodes a string from Base64 format.
    * No blanks or line breaks are allowed within the Base64 encoded input data.
    * @param s  A Base64 String to be decoded.
    * @return   A String containing the decoded data.
    * @throws   IllegalArgumentException If the input is not valid Base64 encoded data.
    */
    public static String decodeString (String s) {
       return new String(decode(s)); }

    /**
    * Decodes a byte array from Base64 format and ignores line separators, tabs and blanks.
    * CR, LF, Tab and Space characters are ignored in the input data.
    * This method is compatible with sun.misc.BASE64Decoder.decodeBuffer(String).
    * @param s  A Base64 String to be decoded.
    * @return   An array containing the decoded data bytes.
    * @throws   IllegalArgumentException If the input is not valid Base64 encoded data.
    */
    public static byte[] decodeLines (String s) {
       char[] buf = new char[s.length()];
       int p = 0;
       for (int ip = 0; ip < s.length(); ip++) {
          char c = s.charAt(ip);
          if (c != ' ' && c != '\r' && c != '\n' && c != '\t')
             buf[p++] = c; }
       return decode(buf, 0, p); }

    /**
    * Decodes a byte array from Base64 format.
    * No blanks or line breaks are allowed within the Base64 encoded input data.
    * @param s  A Base64 String to be decoded.
    * @return   An array containing the decoded data bytes.
    * @throws   IllegalArgumentException If the input is not valid Base64 encoded data.
    */
    public static byte[] decode (String s) {
       return decode(s.toCharArray()); }

    /**
    * Decodes a byte array from Base64 format.
    * No blanks or line breaks are allowed within the Base64 encoded input data.
    * @param in  A character array containing the Base64 encoded data.
    * @return    An array containing the decoded data bytes.
    * @throws    IllegalArgumentException If the input is not valid Base64 encoded data.
    */
    public static byte[] decode (char[] in) {
       return decode(in, 0, in.length); }

    /**
    * Decodes a byte array from Base64 format.
    * No blanks or line breaks are allowed within the Base64 encoded input data.
    * @param in    A character array containing the Base64 encoded data.
    * @param iOff  Offset of the first character in in to be processed.
    * @param iLen  Number of characters to process in in, starting at iOff.
    * @return      An array containing the decoded data bytes.
    * @throws      IllegalArgumentException If the input is not valid Base64 encoded data.
    */
    public static byte[] decode (char[] in, int iOff, int iLen) {
       if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4.");
       while (iLen > 0 && in[iOff+iLen-1] == '=') iLen--;
       int oLen = (iLen*3) / 4;
       byte[] out = new byte[oLen];
       int ip = iOff;
       int iEnd = iOff + iLen;
       int op = 0;
       while (ip < iEnd) {
          int i0 = in[ip++];
          int i1 = in[ip++];
          int i2 = ip < iEnd ? in[ip++] : 'A';
          int i3 = ip < iEnd ? in[ip++] : 'A';
          if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127)
             throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
          int b0 = map2[i0];
          int b1 = map2[i1];
          int b2 = map2[i2];
          int b3 = map2[i3];
          if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0)
             throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
          int o0 = ( b0       <<2) | (b1>>>4);
          int o1 = ((b1 & 0xf)<<4) | (b2>>>2);
          int o2 = ((b2 &   3)<<6) |  b3;
          out[op++] = (byte)o0;
          if (op



9> KARASZI Istv..:

另一个迟到的答案,但我的基准测试显示Jetty的Base64编码器的实现非常快.没有MiGBase64快,但比iHarder Base64快.

import org.eclipse.jetty.util.B64Code;

final String decoded = B64Code.decode(encoded, "UTF-8");

我也做了一些基准测试:

      library     |    encode    |    decode   
------------------+--------------+-------------
 'MiGBase64'      |  10146001.00 |  6426446.00
 'Jetty B64Code'  |   8846191.00 |  3101361.75
 'iHarder Base64' |   3259590.50 |  2505280.00
 'Commons-Codec'  |    241318.04 |   255179.96

这些是运行/秒,所以越高越好.



10> Vassilis Bla..:

给出了javax.xml.bind.DatatypeConverter的测试编码/解码示例,使用方法parseBase64Binary()和printBase64Binary()引用@ jeremy-ross和@nightfirecat的答案.

@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);
}

结果:

INFO - Hello World encoded=> SGVsbG8gV29ybGQ=
INFO - SGVsbG8gV29ybGQ= decoded=> Hello World



11> 小智..:

如果您更喜欢基于性能的解决方案,那么您可以使用"MiGBase64"

http://migbase64.sourceforge.net/

public class Base64Test {
    public static void main(String[] args) {
    String encodeToString = Base64.encodeToString("JavaTips.net".getBytes(), true);
    System.out.println("encodeToString " + encodeToString);
    byte[] decodedBytes = Base64.decode(encodeToString.getBytes());
    System.out.println("decodedBytes " + new String(decodedBytes));
    }
}

推荐阅读
家具销售_903
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有