base64应用场景:e-mail、密钥、证书
相关jar包: bcprov-jdk15on-1.52.jar 、commons-codec-1.10.jar
代码示例:
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.IOException;
public class Main {
private static String URL="Hello World!";
public static void main(String[] args) {
jdkBase64();
ccBase64();
bcBase64();
}
//jdk
public static void jdkBase64(){
BASE64Encoder encoder=new BASE64Encoder();
String jdkBase64URL= encoder.encode(URL.getBytes());
System.out.println("jdkBase64URL: " + jdkBase64URL);
BASE64Decoder decoder=new BASE64Decoder();
try {
String url=new String(decoder.decodeBuffer(jdkBase64URL));
System.out.println("URL:"+url );
} catch (IOException e) {
e.printStackTrace();
}
}
//cc
public static void ccBase64(){
byte[] ccBase64URL= Base64.encodeBase64(URL.getBytes());
String encodeUrl=new String(ccBase64URL);
System.out.println("encodeUrl:" + encodeUrl);
byte[] decodeByte= Base64.decodeBase64(ccBase64URL);
String decodeUrl=new String(decodeByte);
System.out.println("decodeUrl:"+decodeUrl);
}
//bc
public static void bcBase64(){
byte[] bcBase64URL = org.bouncycastle.util.encoders.Base64.encode(URL.getBytes());
String encodeUrl=new String(bcBase64URL);
System.out.println("encodeUrl:" + encodeUrl);
byte[] decodeByte= org.bouncycastle.util.encoders.Base64.decode(bcBase64URL);
String decodeUrl=new String(decodeByte);
System.out.println("decodeUrl:"+decodeUrl);
}
}
控制台输出: