Base64编码的java实现
Java本身是提供了Base64编码的工具包的,做项目的时候自己实现了个,在这里记录一下:
1 /** Base64编码数组 */ 2 private static final String base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; 3 4 /** 5 * Base64 编码 6 * @param str 待编码字符串 7 * @return 8 */ 9 public static String base64encode(String str) { 10 String out = ""; 11 int i = 0; 12 int len = str.length(); 13 int c1, c2, c3; 14 while (i < len) { 15 c1 = str.charAt(i++) & 0xff; 16 if (i == len) { 17 out += base64EncodeChars.charAt(c1 >> 2); 18 out += base64EncodeChars.charAt((c1 & 0x3) << 4); 19 out += "=="; 20 break; 21 } 22 c2 = str.charAt(i++); 23 if (i == len) { 24 out += base64EncodeChars.charAt(c1 >> 2); 25 out += base64EncodeChars.charAt(((c1 & 0x3) << 4) 26 | ((c2 & 0xF0) >> 4)); 27 out += base64EncodeChars.charAt((c2 & 0xF) << 2); 28 out += "="; 29 break; 30 } 31 c3 = str.charAt(i++); 32 out += base64EncodeChars.charAt(c1 >> 2); 33 out += base64EncodeChars.charAt(((c1 & 0x3) << 4) 34 | ((c2 & 0xF0) >> 4)); 35 out += base64EncodeChars.charAt(((c2 & 0xF) << 2) 36 | ((c3 & 0xC0) >> 6)); 37 out += base64EncodeChars.charAt(c3 & 0x3F); 38 } 39 return out; 40 }
如果想生成URL安全的Base64编码,则需要将里面的"+"替换为"-",将"/"替换为"_"
1 /** 2 * 将Base64编码转换为URL安全的Base64编码 3 * @param str Base64编码的字符串 4 * @return 5 */ 6 private static String safe64(String str) { 7 String result = str.replace("+", "-"); 8 return result.replace("/", "_"); 9 }