package com.company;
public class zbase64 {
private static final char[] Base64ByteToStr = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
private static final int RANGE = 255;
private static byte[] StrToBase64Byte = new byte[128];
public static String Base64Encode(byte[] bytes) {
StringBuilder res = new StringBuilder();
for (int i = 0; i <= bytes.length - 1; i += 3) {
byte[] enBytes = new byte[4];
byte tmp = 0;
for (int k = 0; k <= 2; k++) {
if (i + k <= bytes.length - 1) {
enBytes[k] = (byte) (((bytes[i + k] & 255) >>> ((k * 2) + 2)) | tmp);
tmp = (byte) ((((bytes[i + k] & 255) << (((2 - k) * 2) + 2)) & 255) >>> 2);
} else {
enBytes[k] = tmp;
tmp = 64;
}
}
enBytes[3] = tmp;
for (int k2 = 0; k2 <= 3; k2++) {
if (enBytes[k2] <= 63) {
res.append(Base64ByteToStr[enBytes[k2]]);
} else {
res.append('=');
}
}
}
return res.toString();
}
}
主函数调用:
String zbx = zbase64.Base64Encode(bs.getBytes(StandardCharsets.UTF_8));
System.out.println("自编写base64加密:"+zbx);
运行结果:
自编写base64加密:6YCG5ZCR5pyJ5L2gYQ==