Base64 Encoding in Java

2018-12-31 03:33发布

I'm using Eclipse. I have the following line of code:

wr.write(new sun.misc.BASE64Encoder().encode(buf));

Eclipse marks this line as an error. I imported the required libraries:

import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;

But again, both of them are shown as errors. I found a similar post here.

I used Apache Commons as the solution suggested by including:

import org.apache.commons.*;

and importing the JAR files downloaded from: http://commons.apache.org/codec/

But the problem still exists. Eclipse still shows the errors previously mentioned; please advise.

标签: java base64
16条回答
笑指拈花
2楼-- · 2018-12-31 03:50

Google Guava is a good choice to encode and decode base64 data:

POM config:

<dependency>
   <artifactId>guava</artifactId>
   <groupId>com.google.guava</groupId>
   <type>jar</type>
   <version>14.0.1</version>
</dependency>

Sample code:

String inputContent = "Hello Việt Nam";
String base64String = BaseEncoding.base64().encode(inputContent.getBytes("UTF-8"));
//decode
System.out.println("Base64:" + base64String);//SGVsbG8gVmnhu4d0IE5hbQ==
byte[] contentInBytes = BaseEncoding.base64().decode(base64String);
System.out.println("Source content: " + new String(contentInBytes, "UTF-8"));//Hello Việt Nam
查看更多
素衣白纱
3楼-- · 2018-12-31 03:52

Here are my two cents... Java 8 does contain its own implementation of Base64. However, I found one slightly disturbing difference. To illustrate, I will provide a code example:

My CODEC wrapper:

public interface MyCodec
{
  static String apacheDecode(String encodedStr)
  {
     return new String(Base64.decodeBase64(encodedStr), Charset.forName("UTF-8"));
  }

  static String apacheEncode(String decodedStr)
  {
      byte[] decodedByteArr = decodedStr.getBytes(Charset.forName("UTF-8"));
      return Base64.encodeBase64String(decodedByteArr);
  }

  static String javaDecode(String encodedStr)
  {
      return new String(java.util.Base64.getDecoder().decode(encodedStr), Charset.forName("UTF-8"));
  }

  static String javaEncode(String decodedStr)
  {
    byte[] decodedByteArr = decodedStr.getBytes(Charset.forName("UTF-8"));
    return java.util.Base64.getEncoder().encodeToString(decodedByteArr);
  }
}

Test Class:

public class CodecDemo
{
  public static void main(String[] args)
  {
    String decodedText = "Hello World!";

    String encodedApacheText = MyCodec.apacheEncode(decodedText);
    String encodedJavaText = MyCodec.javaEncode(decodedText);

    System.out.println("Apache encoded text: " + MyCodec.apacheEncode(encodedApacheText));
    System.out.println("Java encoded text: " + MyCodec.javaEncode(encodedJavaText));

    System.out.println("Encoded results equal: " + encodedApacheText.equals(encodedJavaText));

    System.out.println("Apache decode Java: " + MyCodec.apacheDecode(encodedJavaText));
    System.out.println("Java decode Java: " + MyCodec.javaDecode(encodedJavaText));

    System.out.println("Apache decode Apache: " + MyCodec.apacheDecode(encodedApacheText));
    System.out.println("Java decode Apache: " + MyCodec.javaDecode(encodedApacheText));
  }
}

OUTPUT:

Apache encoded text: U0dWc2JHOGdWMjl5YkdRaA0K

Java encoded text: U0dWc2JHOGdWMjl5YkdRaA==
Encoded results equal: false
Apache decode Java: Hello World!
Java decode Java: Hello World!
Apache decode Apache: Hello World!
Exception in thread "main" java.lang.IllegalArgumentException: Illegal base64 character d
    at java.util.Base64$Decoder.decode0(Base64.java:714)
    at java.util.Base64$Decoder.decode(Base64.java:526)
    at java.util.Base64$Decoder.decode(Base64.java:549)

Notice that the Apache encoded text contain additional line breaks (white spaces) at the end. Therefore, in order for my CODEC to yield the same result regardless of Base64 implementation, I had to call trim() on the Apache encoded text. In my case, I simply added the aforementioned method call to the my CODEC's apacheDecode() as follows:

return Base64.encodeBase64String(decodedByteArr).trim();

Once this change was made, the results are what I expected to begin with:

Apache encoded text: U0dWc2JHOGdWMjl5YkdRaA==
Java encoded text: U0dWc2JHOGdWMjl5YkdRaA==
Encoded results equal: true
Apache decode Java: Hello World!
Java decode Java: Hello World!
Apache decode Apache: Hello World!
Java decode Apache: Hello World!

Maybe someone could comment as to why this is, but I found my workaround as an acceptable compromise.

查看更多
美炸的是我
4楼-- · 2018-12-31 03:53

Simple example with Java 8:

import java.util.Base64;

String str = "your string";
String encodedStr = Base64.getEncoder().encodeToString(str.getBytes("utf-8"));
查看更多
只靠听说
5楼-- · 2018-12-31 03:54

You can also convert using base64 encoding. To do this you can use javax.xml.bind.DatatypeConverter#printBase64Binary method

For example:

byte[] salt = new byte[] { 50, 111, 8, 53, 86, 35, -19, -47 };
System.out.println(DatatypeConverter.printBase64Binary(salt));
查看更多
深知你不懂我心
6楼-- · 2018-12-31 03:55

For java 6-7 best option is to borrow code from Android repository. It has no dependencies.

https://github.com/android/platform_frameworks_base/blob/master/core/java/android/util/Base64.java

查看更多
浪荡孟婆
7楼-- · 2018-12-31 03:55

On Android, use the static methods of the android.util.Base64 utility class. The referenced documentation says that the Base64 class was added in API level 8 (Froyo).

import android.util.Base64;

byte[] encodedBytes = Base64.encode("Test".getBytes());
Log.d("tag", "encodedBytes " + new String(encodedBytes));

byte[] decodedBytes = Base64.decode(encodedBytes);
Log.d("tag", "decodedBytes " + new String(decodedBytes));
查看更多
登录 后发表回答