实现Base64算法的几种方式
- 通过JDK
- 通过Apache的Commons Codec
- 通过Bouncy Castle
下面是具体的实现方式类
package com.fch.base64;
import java.io.IOException;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
* Java实现Base64算法
*
* @author admin
*
*/
public class JavaBase64Test {
/**
* 算法实现方式
*
* 1.JDK
*
* 2。Commons Codec(Apache)
*
* 3.Bouncy Castle
*
* 应用场景 e-mail、密钥、证书文件
*/
public static void main(String[] args) {
jdkBase64("java security base64");
commonsCodesBase64("java security base64");
bouncyCastleBase64("java security base64");
}
/**
* JDK 实现Base64(不推荐)
*
* @param encryStr
* @throws IOException
*/
public static void jdkBase64(String encryStr) {
try {
System.out
.println("====================JDK Base64====================");
BASE64Encoder encoder = new BASE64Encoder();
String encodeStr = encoder.encode(encryStr.getBytes());
System.out.println("encode : " + encodeStr);
BASE64Decoder decoder = new BASE64Decoder();
byte[] by;
by = decoder.decodeBuffer(encodeStr);
String byStr = new String(by);
System.out.println("decode : " + byStr);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println();
}
/**
* Commons Codec 实现Base64
*
* @param encoderStr
*/
public static void commonsCodesBase64(String encoderStr) {
System.out
.println("====================Commons Codec Base64====================");
byte[] encodeBytes = Base64.encodeBase64(encoderStr.getBytes());
System.out.println("encode : " + new String(encodeBytes));
byte[] decodeBytes = Base64.decodeBase64(encodeBytes);
System.out.println("decode : " + new String(decodeBytes));
System.out.println();
}
/**
* Bouncy Castle 实现Base64
*
* 感觉速度比较慢
*
* @param encoderStr
*/
public static void bouncyCastleBase64(String encoderStr) {
System.out
.println("====================Bouncy Castle Base64====================");
byte[] encodeBytes = org.bouncycastle.util.encoders.Base64
.encode(encoderStr.getBytes());
System.out.println("encode : " + new String(encodeBytes));
byte[] decodeBytes = org.bouncycastle.util.encoders.Base64
.decode(encodeBytes);
System.out.println("decode : " + new String(decodeBytes));
System.out.println();
}
}
其中Commons Codec和Bouncy Castle属于第三方提供,需要下载相应的jar包,后者jar包与jdk的版本相对应,前者对jdk没有太多依赖。
提供两个jar包的下载链接:
http://download.youkuaiyun.com/detail/fucaihe/8633707
http://download.youkuaiyun.com/detail/fucaihe/8633703