Java本身是提供了Base64编码的工具包的,做项目的时候自己实现了个,在这里记录一下:
/** Base64编码数组 */
private static final String base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; /**
* Base64 编码
* @param str 待编码字符串
* @return
*/
public static String base64encode(String str) {
String out = "";
int i = 0;
int len = str.length();
int c1, c2, c3;
while (i < len) {
c1 = str.charAt(i++) & 0xff;
if (i == len) {
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt((c1 & 0x3) << 4);
out += "==";
break;
}
c2 = str.charAt(i++);
if (i == len) {
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt(((c1 & 0x3) << 4)
| ((c2 & 0xF0) >> 4));
out += base64EncodeChars.charAt((c2 & 0xF) << 2);
out += "=";
break;
}
c3 = str.charAt(i++);
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt(((c1 & 0x3) << 4)
| ((c2 & 0xF0) >> 4));
out += base64EncodeChars.charAt(((c2 & 0xF) << 2)
| ((c3 & 0xC0) >> 6));
out += base64EncodeChars.charAt(c3 & 0x3F);
}
return out;
}
如果想生成URL安全的Base64编码,则需要将里面的"+"替换为"-",将"/"替换为"_"
/**
* 将Base64编码转换为URL安全的Base64编码
* @param str Base64编码的字符串
* @return
*/
private static String safe64(String str) {
String result = str.replace("+", "-");
return result.replace("/", "_");
}