BASE64算法主要用于转换二进制数据为ASCII字符串格式。Java语言提供了一个非常好的BASE64算法的实现,即Apache Commons Codec工具包。
encodeBase64和decodeBase64 JAVA:
/***
* encode by Base64
*/
public static String encodeBase64(byte[]input) throws Exception{
Class clazz = Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
Method mainMethod = clazz.getMethod("encode", byte[].class);
mainMethod.setAccessible(true);
Object retObj = mainMethod.invoke(null, new Object[]{input});
return (String)retObj;
}
/***
* decode by Base64
*/
public static byte[] decodeBase64(String input) throws Exception{
Class clazz = Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
Method mainMethod = clazz.getMethod("decode", String.class);
mainMethod.setAccessible(true);
Object retObj = mainMethod.invoke(null, input);
return (byte[])retObj;
}
应用:
String str = "Hello World";
byte[] encodestr = Base64.encodeBase64(str.getBytes("UTF-8"));
System.out.println("RESULT: " + new String(encodestr));
输出的结果是:RESULT:
SGVsbG8gV29ybGQ
输出的字符串是 hello world的8位二进制值连接在一起,然后以6位为分组。随后每个组都被转换成一个单独的数字并映射到BASE64的索引。