import java.lang.Exception;
public class Base64
{ //编码表
static private byte[] alphabet = {
(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E',
(byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J',
(byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O',
(byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T',
(byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y',
(byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd',
(byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i',
(byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n',
(byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's',
(byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x',
(byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2',
(byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7',
(byte) '8', (byte) '9', (byte) '+', (byte) '/', (byte) '='
};
//解码表
static private byte[] codes = new byte[256];
static {
for (int i = 0; i < 256; i++)
codes[i] = -1;
for (int i = 'A'; i <= 'Z'; i++)
codes[i] = (byte) (i - 'A');
for (int i = 'a'; i <= 'z'; i++)
codes[i] = (byte) (26 + i - 'a');
for (int i = '0'; i <= '9'; i++)
codes[i] = (byte) (52 + i - '0');
codes['+'] = 62;
codes['/'] = 63;
}
//将原始数据编码为base64编码
static public byte[] encode(byte[] source){
byte[] out = new byte[((source.length + 2) / 3) * 4];
for (int i = 0, j = 0; i < source.length; i += 3, j += 4){
boolean q = false,t = false;
int val = (0xFF & (int) source[i]);
val <<= 8;
if ((i + 1) < source.length){
val |= (0xFF & (int) source[i + 1]);
t = true;
}
val <<= 8;
if ((i + 2) < source.length){
val |= (0xFF & (int) source[i + 2]);
q = true;
}
out[j + 3] = alphabet[(q ? (val & 0x3F) : 64)];
val >>= 6;
out[j + 2] = alphabet[(t ? (val & 0x3F) : 64)];
val >>= 6;
out[j + 1] = alphabet[val & 0x3F];
val >>= 6;
out[j + 0] = alphabet[val & 0x3F];
}
return out;
}
//将base64编码的数据解码成原始数据
static public byte[] decode(byte[] dest){
int len = ((dest.length + 3) / 4) * 3;
if(dest.length > 0 && dest[dest.length - 1] == '=')
--len;
if(dest.length > 1 && dest[dest.length - 2] == '=')
--len;
byte[] out = new byte[len];
int a = 0;
int b = 0;
int c = 0;
for(int i = 0; i < dest.length; i++){
int value = codes[dest[i] & 0xFF];
if(value >= 0){
b <<= 6;
a += 6;
b |= value;
if(a >= 8)
{
a -= 8;
out[c++] = (byte)((b >> a) & 0xff);
}
}
}
if(c != out.length)
throw new Error("miscalculated dest length!");
return out;
}
public static void main(String[] args) throws Exception
{
//加密成base64
String strSrc = "你好,欢迎来到jim20的博客";
String strOut = new String(Base64.encode(strSrc.getBytes()));
System.out.println(strOut);
String strOut2 = new String(Base64.decode(strOut.getBytes()));
System.out.println(strOut2);
}
}
Base64编码和解码
最新推荐文章于 2024-03-26 08:45:00 发布