Base64 加密


       Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,大家可以查看RFC2045~RFC2049,上面有MIME的详细规范。Base64编码可用于在HTTP环境下传递较长的标识信息。例如,在Java Persistence系统Hibernate中,就采用了Base64来将一个较长的唯一标识符(一般为128-bit的UUID)编码为一个字符串,用作HTTP表单和HTTP GET URL中的参数。在其他应用程序中,也常常需要把二进制数据编码为适合放在URL(包括隐藏表单域)中的形式。此时,采用Base64编码不仅比较简短,同时也具有不可读性,即所编码的数据不会被人用肉眼所直接看到。



1简介编辑

标准的Base64并不适合直接放在URL里传输,因为URL编码器会把标准Base64中的“/”和“+” 字符变为形如“%XX”的形式,而这些“%”号在存入数据库时还需要再进行转换,因为ANSI SQL中已将“%”号用作 通配符
为解决此问题,可采用一种用于URL的改进Base64编码,它不在末尾填充'='号,并将标准Base64中的“+”和“/”分别改成了“_”和“-”,这样就免去了在URL编解码和数据库存储时所要作的转换,避免了编码信息长度在此过程中的增加,并统一了数据库、表单等处对象 标识符的格式。
另有一种用于 正则表达式的改进Base64变种,它将“+”和“/”改成了“!”和“-”,因为“+”,“*”以及前面在IRCu中用到的“[”和“]”在正则表达式中都可能具有特殊含义。
此外还有一些变种,它们将“+/”改为“_-”或“._”(用作 编程语言中的 标识符名称)或“.-”(用于XML中的Nmtoken)甚至“_:”(用于XML中的Name)。
Base64要求把每三个8Bit的 字节转换为四个6Bit的字节(3*8 = 4*6 = 24),然后把6Bit再添两位高位0,组成四个8Bit的字节,也就是说,转换后的字符串理论上将要比原来的长1/3。
规则
关于这个编码的规则:
①.把3个 字符变成4个字符。
②每76个 字符加一个换行符。
③.最后的结束符也要处理。
这样说会不会太抽象了?不怕,我们来看一个例子:
转换前 11111111, 11111111, 11111111 (二进制)
转换后 00111111, 00111111, 00111111, 00111111 (二进制)
应该很清楚了吧?上面的三个 字节是原文,下面的四个字节是转换后的Base64编码,其前两位均为0。
转换后,我们用一个码表来得到我们想要的字符串(也就是最终的Base64编码),这个表是这样的:(摘自RFC2045)
转换表
Table 1: The Base64 Alphabet
索引
对应字符
索引
对应字符
索引
对应字符
索引
对应字符
0
A
17
R
34
i
51
z
1
B
18
S
35
j
52
0
2
C
19
T
36
k
53
1
3
D
20
U
37
l
54
2
4
E
21
V
38
m
55
3
5
F
22
W
39
n
56
4
6
G
23
X
40
o
57
5
7
H
24
Y
41
p
58
6
8
I
25
Z
42
q
59
7
9
J
26
a
43
r
60
8
10
K
27
b
44
s
61
9
11
L
28
c
45
t
62
+
12
M
29
d
46
u
63
/
13
N
30
e
47
v
   
14
O
31
f
48
w
   
15
P
32
g
49
x
   
16
Q
33
h
50
y
   
举例
让我们再来看一个实际的例子,加深印象!
转换前 101 0,1101 1011 10,10 0111 0110
转换后 0010101,1 00011011 00,101001 ,00110110
十进制 43 27 41 54
对应码表中的值 r b p 2
所以上面的24位编码,编码后的Base64值为 rbp2
解码同理,把 rbq2 的二进制位连接上再重组得到三个8位值,得出原码。
(解码只是编码的逆过程,在此我就不多说了,另外有关MIME的RFC还是有很多的,如果需要详细情况请自行查找。)
第一个字节,根据源字节的第一个字节处理。
规则:源第一字节右移两位,去掉低2位,高2位补零。
既:00 + 高6位
第二个字节,根据源字节的第一个字节和第二个字节联合处理。
规则如下,第一个字节高6位去掉左移四位,第二个字节右移四位
即:源第一字节低2位 + 源第2字节高4位
第三个字节,根据源字节的第二个字节和第三个字节联合处理,
规则第二个字节去掉高4位并左移两位(得高6位),第三个字节右移6位并去掉高6位(得低2位),相加即可
第四个字节,规则,源第三字节去掉高2位即可
根据base64的编码规则,每76个字符需要一个换行
// 用更接近于 编程的思维来说,编码的过程是这样的:
//第一个 字符通过右移2位获得第一个目标字符的Base64表位置,根据这个数值取到表上相应的字符,就是第一//个目标字符。
// 然后将第一个 字符左移4位加上第二个字符右移4位,即获得第二个目标字符。
//再将第二个 字符左移2位加上第三个字符右移6位,获得第三个目标字符。
//最后取第三个 字符的右6位即获得第四个目标字符。
//在以上的每一个步骤之后,再把结果与 0x3F 进行 AND  位操作,就可以得到编码后的 字符了。
可是等等……聪明的你可能会问到,原文的 字节数量应该是3的倍数啊,如果这个条件不能满足的话,那该怎么办呢?
我们的解决办法是这样的:原文剩余的字节根据编码规则继续单独转(1变2,2变3;不够的位数用0补全),再用=号补满4个字节。这就是为什么有些Base64编码会以一个或两个等号结束的原因,但等号最多只有两个。因为:
余数 = 原文字节数 MOD 3
所以余数任何情况下都只可能是0,1,2这三个数中的一个。如果余数是0的话,就表示原文字节数正好是3的倍数(最理想的情况啦)。如果是1的话,为了让Base64编码是3的倍数,就要补2个等号;同理,如果是2的话,就要补1个等号。

2原理编辑

先以“ 迅雷下载”为例: 很多下载类网站都提供“迅雷下载”的链接,其地址通常是加密的迅雷专用下载地址。
其实 迅雷的“专用地址”也是用Base64加密的,其加密过程如下:
一、在地址的前后分别添加AA和ZZ
二、对新的字符串进行Base64编码
另:  Flashget的与 迅雷类似,只不过在第一步时加的“料”不同罢了,Flashget在地址前后加的“料”是[FLASHGET]
而QQ旋风的干脆不加料,直接就对地址进行Base64编码了

3应用编辑

Base64编码可用于在HTTP环境下传递较长的标识信息。例如,在Java Persistence系统Hibernate中,就采用了Base64来将一个较长的唯一 标识符(一般为128-bit的UUID)编码为一个字符串,用作HTTP表单和HTTP GET URL中的参数。在其他 应用程序中,也常常需要把二进制数据编码为适合放在URL(包括隐藏表单域)中的形式。此时,采用Base64编码不仅比较简短,同时也具有不可读性,即所编码的数据不会被人用肉眼所直接看到。
然而,标准的Base64并不适合直接放在URL里传输,因为URL编码器会把标准Base64中的“/”和“+”字符变为形如“%XX”的形式,而这些“%”号在存入数据库时还需要再进行转换,因为ANSI SQL中已将“%”号用作通配符。
为解决此问题,可采用一种用于URL的改进Base64编码,它不在末尾填充'='号,并将标准Base64中的“+”和“/”分别改成了“*”和“-”,这样就免去了在URL编解码和数据库存储时所要作的转换,避免了编码信息长度在此过程中的增加,并统一了数据库、表单等处对象 标识符的格式。
另有一种用于正则表达式的改进Base64变种,它将“+”和“/”改成了“!”和“-”,因为“+”,“*”以及前面在IRCu中用到的“[”和“]”在正则表达式中都可能具有特殊含义。
此外还有一些变种,它们将“+/”改为“_-”或“._”(用作编程语言中的标识符名称)或“.-”(用于XML中的Nmtoken)甚至“_:”(用于XML中的Name)。
其他应用
Mozilla Thunderbird和Evolution用Base64来保密 电子邮件密码
Base64 也会经常用作一个简单的“加密”来保护某些数据,而真正的加密通常都比较繁琐。
垃圾讯息传播者用Base64来避过反垃圾邮件工具,因为那些工具通常都不会翻译Base64的讯息。
在LDIF档案,Base64用作编码字串。

4代码实现

import java.util.Arrays;
import java.io.UnsupportedEncodingException;
 
/**
 * One of the <b>fastest</b> Base64 encoder/decoder implementations. Base64
 * encoding is defined in RFC 2045.
 */
public class Base64 {

 private static final char[] CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
 .toCharArray();
 private static final int[] INV = new int[256];
 
 static {
 Arrays.fill(INV, -1);
 for (int i = 0, iS = CHARS.length; i < iS; i++) {
 INV[CHARS[i]] = i;
 }
 INV['='] = 0;
 }
 
 /**
 * Returns Base64 characters, a clone of used array.
 */
 public static char[] getAlphabet() {
 return CHARS.clone();
 }
 
 // ---------------------------------------------------------------- char[]
 public static char[] encodeToChar(String s) {
 try {
 return encodeToChar(s.getBytes("UTF-8"), false);
 } catch (UnsupportedEncodingException ignore) {
 return null;
 }
 }
 
 public static char[] encodeToChar(byte[] arr) {
 return encodeToChar(arr, false);
 }
 
 /**
 * Encodes a raw byte array into a BASE64 <code>char[]</code>.
 */
 public static char[] encodeToChar(byte[] arr, boolean lineSeparator) {
 int len = arr != null ? arr.length : 0;
 if (len == 0) {
 return new char[0];
 }
 
 int evenlen = (len / 3) * 3;
 int cnt = ((len - 1) / 3 + 1) << 2;
 int destLen = cnt + (lineSeparator ? (cnt - 1) / 76 << 1 : 0);
 char[] dest = new char[destLen];
 
 for (int s = 0, d = 0, cc = 0; s < evenlen;) {
 int i = (arr[s++] & 0xff) << 16 | (arr[s++] & 0xff) << 8
 | (arr[s++] & 0xff);
 
 dest[d++] = CHARS[(i >>> 18) & 0x3f];
 dest[d++] = CHARS[(i >>> 12) & 0x3f];
 dest[d++] = CHARS[(i >>> 6) & 0x3f];
 dest[d++] = CHARS[i & 0x3f];
 
 if (lineSeparator && (++cc == 19) && (d < (destLen - 2))) {
 dest[d++] = '\r';
 dest[d++] = '\n';
 cc = 0;
 }
 }
 
 int left = len - evenlen; // 0 - 2.
 if (left > 0) {
 int i = ((arr[evenlen] & 0xff) << 10)
 | (left == 2 ? ((arr[len - 1] & 0xff) << 2) : 0);
 
 dest[destLen - 4] = CHARS[i >> 12];
 dest[destLen - 3] = CHARS[(i >>> 6) & 0x3f];
 dest[destLen - 2] = left == 2 ? CHARS[i & 0x3f] : '=';
 dest[destLen - 1] = '=';
 }
 return dest;
 }
 
 /**
 * Decodes a BASE64 encoded char array.
 */
 public byte[] decode(char[] arr) {
 int length = arr.length;
 if (length == 0) {
 return new byte[0];
 }
 
 int sndx = 0, endx = length - 1;
 int pad = arr[endx] == '=' ? (arr[endx - 1] == '=' ? 2 : 1) : 0;
 int cnt = endx - sndx + 1;
 int sepCnt = length > 76 ? (arr[76] == '\r' ? cnt / 78 : 0) << 1 : 0;
 int len = ((cnt - sepCnt) * 6 >> 3) - pad;
 byte[] dest = new byte[len];
 
 int d = 0;
 for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
 int i = INV[arr[sndx++]] << 18 | INV[arr[sndx++]] << 12
 | INV[arr[sndx++]] << 6 | INV[arr[sndx++]];
 
 dest[d++] = (byte) (i >> 16);
 dest[d++] = (byte) (i >> 8);
 dest[d++] = (byte) i;
 
 if (sepCnt > 0 && ++cc == 19) {
 sndx += 2;
 cc = 0;
 }
 }
 
 if (d < len) {
 int i = 0;
 for (int j = 0; sndx <= endx - pad; j++) {
 i |= INV[arr[sndx++]] << (18 - j * 6);
 }
 for (int r = 16; d < len; r -= 8) {
 dest[d++] = (byte) (i >> r);
 }
 }
 
 return dest;
 }
 
 // ---------------------------------------------------------------- byte
 public static byte[] encodeToByte(String s) {
 try {
 return encodeToByte(s.getBytes("UTF-8"), false);
 } catch (UnsupportedEncodingException ignore) {
 return null;
 }
 }
 
 public static byte[] encodeToByte(byte[] arr) {
 return encodeToByte(arr, false);
 }
 
 /**
 * Encodes a raw byte array into a BASE64 <code>byte[]</code>.
 */
 public static byte[] encodeToByte(byte[] arr, boolean lineSep) {
 int len = arr != null ? arr.length : 0;
 if (len == 0) {
 return new byte[0];
 }
 
 int evenlen = (len / 3) * 3;
 int cnt = ((len - 1) / 3 + 1) << 2;
 int destlen = cnt + (lineSep ? (cnt - 1) / 76 << 1 : 0);
 byte[] dest = new byte[destlen];
 
 for (int s = 0, d = 0, cc = 0; s < evenlen;) {
 int i = (arr[s++] & 0xff) << 16 | (arr[s++] & 0xff) << 8
 | (arr[s++] & 0xff);
 
 dest[d++] = (byte) CHARS[(i >>> 18) & 0x3f];
 dest[d++] = (byte) CHARS[(i >>> 12) & 0x3f];
 dest[d++] = (byte) CHARS[(i >>> 6) & 0x3f];
 dest[d++] = (byte) CHARS[i & 0x3f];
 
 if (lineSep && ++cc == 19 && d < destlen - 2) {
 dest[d++] = '\r';
 dest[d++] = '\n';
 cc = 0;
 }
 }
 
 int left = len - evenlen;
 if (left > 0) {
 int i = ((arr[evenlen] & 0xff) << 10)
 | (left == 2 ? ((arr[len - 1] & 0xff) << 2) : 0);
 
 dest[destlen - 4] = (byte) CHARS[i >> 12];
 dest[destlen - 3] = (byte) CHARS[(i >>> 6) & 0x3f];
 dest[destlen - 2] = left == 2 ? (byte) CHARS[i & 0x3f] : (byte) '=';
 dest[destlen - 1] = '=';
 }
 return dest;
 }
 
 /**
 * Decodes a BASE64 encoded byte array.
 */
 public static byte[] decode(byte[] arr) {
 int length = arr.length;
 if (length == 0) {
 return new byte[0];
 }
 
 int sndx = 0, endx = length - 1;
 int pad = arr[endx] == '=' ? (arr[endx - 1] == '=' ? 2 : 1) : 0;
 int cnt = endx - sndx + 1;
 int sepCnt = length > 76 ? (arr[76] == '\r' ? cnt / 78 : 0) << 1 : 0;
 int len = ((cnt - sepCnt) * 6 >> 3) - pad;
 byte[] dest = new byte[len];
 
 int d = 0;
 for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
 int i = INV[arr[sndx++]] << 18 | INV[arr[sndx++]] << 12
 | INV[arr[sndx++]] << 6 | INV[arr[sndx++]];
 
 dest[d++] = (byte) (i >> 16);
 dest[d++] = (byte) (i >> 8);
 dest[d++] = (byte) i;
 
 if (sepCnt > 0 && ++cc == 19) {
 sndx += 2;
 cc = 0;
 }
 }
 
 if (d < len) {
 int i = 0;
 for (int j = 0; sndx <= endx - pad; j++) {
 i |= INV[arr[sndx++]] << (18 - j * 6);
 }
 for (int r = 16; d < len; r -= 8) {
 dest[d++] = (byte) (i >> r);
 }
 }
 
 return dest;
 }
 
 // ---------------------------------------------------------------- string
 public static String encodeToString(String s) {
 try {
 return new String(encodeToChar(s.getBytes("UTF-8"), false));
 } catch (UnsupportedEncodingException ignore) {
 return null;
 }
 }
 
 public static String decodeToString(String s) {
 try {
 return new String(decode(s), "UTF-8");
 } catch (UnsupportedEncodingException ignore) {
 return null;
 }
 }
 
 public static String encodeToString(byte[] arr) {
 return new String(encodeToChar(arr, false));
 }
 
 /**
 * Encodes a raw byte array into a BASE64 <code>String</code>.
 */
 public static String encodeToString(byte[] arr, boolean lineSep) {
 return new String(encodeToChar(arr, lineSep));
 }
 
 /**
 * Decodes a BASE64 encoded string.
 */
 public static byte[] decode(String s) {
 int length = s.length();
 if (length == 0) {
 return new byte[0];
 }
 
 int sndx = 0, endx = length - 1;
 int pad = s.charAt(endx) == '=' ? (s.charAt(endx - 1) == '=' ? 2 : 1)
 : 0;
 int cnt = endx - sndx + 1;
 int sepCnt = length > 76 ? (s.charAt(76) == '\r' ? cnt / 78 : 0) << 1
 : 0;
 int len = ((cnt - sepCnt) * 6 >> 3) - pad;
 byte[] dest = new byte[len];
 
 int d = 0;
 for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
 int i = INV[s.charAt(sndx++)] << 18 | INV[s.charAt(sndx++)] << 12
 | INV[s.charAt(sndx++)] << 6 | INV[s.charAt(sndx++)];
 
 dest[d++] = (byte) (i >> 16);
 dest[d++] = (byte) (i >> 8);
 dest[d++] = (byte) i;
 
 if (sepCnt > 0 && ++cc == 19) {
 sndx += 2;
 cc = 0;
 }
 }
 
 if (d < len) {
 int i = 0;
 for (int j = 0; sndx <= endx - pad; j++) {
 i |= INV[s.charAt(sndx++)] << (18 - j * 6);
 }
 for (int r = 16; d < len; r -= 8) {
 dest[d++] = (byte) (i >> r);
 }
 }
 
 return dest;
 }
 
 public static void main(String[] args) {
 long s = System.nanoTime();
 String str = "The quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dog";
 for (int i = 0; i < 100000; i++) {
 Base64.encodeToByte(str);
 }
 long e = System.nanoTime();
 System.out.println(e - s);
 }
 
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值