新浪微博(十三)64位编码转换的实现(Base64类)

来源:互联网 发布:mac os x 如何升级 编辑:程序博客网 时间:2024/06/06 18:49
为什么要使用Base64?

在设计这个编码的时候,我想设计人员最主要考虑了3个问题: 
1.是否加密? 
2.加密算法复杂程度和效率 
3.如何处理传输? 

    加密是肯定的,但是加密的目的不是让用户发送非常安全的Email。这种加密方式主要就是“防君子不防小人”。即达到一眼望去完全看不出内容即可。 
基于这个目的加密算法的复杂程度和效率也就不能太大和太低。和上一个理由类似,MIME协议等用于发送Email的协议解决的是如何收发Email,而并不是如何安全的收发Email。因此算法的复杂程度要小,效率要高,否则因为发送Email而大量占用资源,路就有点走歪了。 

    但是,如果是基于以上两点,那么我们使用最简单的恺撒法即可,为什么Base64看起来要比恺撒法复杂呢?这是因为在Email的传送过程中,由于历史原因,Email只被允许传送ASCII字符,即一个8位字节的低7位。因此,如果您发送了一封带有非ASCII字符(即字节的最高位是1)的Email通过有“历史问题”的网关时就可能会出现问题。网关可能会把最高位置为0!很明显,问题就这样产生了!因此,为了能够正常的传送Email,这个问题就必须考虑!所以,单单靠改变字母的位置的恺撒之类的方案也就不行了。关于这一点可以参考RFC2046。 
基于以上的一些主要原因产生了Base64编码。 
/** *@author coolszy *@date 2011-5-29 *@blog http://blog.csdn.net/coolszy */package tianyi.helper;public class Base64{private static final char last2byte = (char) Integer.parseInt("00000011", 2);private static final char last4byte = (char) Integer.parseInt("00001111", 2);private static final char last6byte = (char) Integer.parseInt("00111111", 2);private static final char lead6byte = (char) Integer.parseInt("11111100", 2);private static final char lead4byte = (char) Integer.parseInt("11110000", 2);private static final char lead2byte = (char) Integer.parseInt("11000000", 2);private static final char[] encodeTable = new char[]{ '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', '+', '/' };/** * Base64 encoding. *  * @param from *            The src data. * @return */public static String encode(byte[] from){StringBuffer to = new StringBuffer((int) (from.length * 1.34) + 3);int num = 0;char currentByte = 0;for (int i = 0; i < from.length; i++){num = num % 8;while (num < 8){switch (num){case 0:currentByte = (char) (from[i] & lead6byte);currentByte = (char) (currentByte >>> 2);break;case 2:currentByte = (char) (from[i] & last6byte);break;case 4:currentByte = (char) (from[i] & last4byte);currentByte = (char) (currentByte << 2);if ((i + 1) < from.length){currentByte |= (from[i + 1] & lead2byte) >>> 6;}break;case 6:currentByte = (char) (from[i] & last2byte);currentByte = (char) (currentByte << 4);if ((i + 1) < from.length){currentByte |= (from[i + 1] & lead4byte) >>> 4;}break;}to.append(encodeTable[currentByte]);num += 6;}}if (to.length() % 4 != 0){for (int i = 4 - to.length() % 4; i > 0; i--){to.append("=");}}return to.toString();}}

参考资料:

1.http://clojure.iteye.com/blog/1102584

2.http://www.5dmail.net/html/2004-1-30/200413084348.htm


原创粉丝点击