当前位置:   article > 正文

Base64编码原理_base64toint

base64toint

转自 http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001399413803339f4bbda5c01fc479cbea98b1387390748000

  1. Base64是一种用64个字符来表示任意二进制数据的方法。
  2. 用记事本打开exe、jpg、pdf这些文件时,我们都会看到一大堆乱码,因为二进制文件包含很多无法显示和打印的字符,所以,如果要让记事本这样的文本处理软件能处理二进制数据,就需要一个二进制到字符串的转换方法。Base64是一种最常见的二进制编码方法。
  3. Base64的原理很简单,首先,准备一个包含64个字符的数组:
  4. ['A', 'B', 'C', ... 'a', 'b', 'c', ... '0', '1', ... '+', '/']
  5. 然后,对二进制数据进行处理,每3个字节一组,一共是3x8=24bit,划为4组,每组正好6个bit:
  6. base64-encode
  7. 这样我们得到4个数字作为索引,然后查表,获得相应的4个字符,就是编码后的字符串。
  8. 所以,Base64编码会把3字节的二进制数据编码为4字节的文本数据,长度增加33%,好处是编码后的文本数据可以在邮件正文、网页等直接显示。
  9. 如果要编码的二进制数据不是3的倍数,最后会剩下1个或2个字节怎么办?Base64用\x00字节在末尾补足后,再在编码的末尾加上1个或2个=号,表示补了多少字节,解码的时候,会自动去掉。
  10. Python内置的base64可以直接进行base64的编解码:
  11. >>> import base64
  12. >>> base64.b64encode('binary\x00string')
  13. 'YmluYXJ5AHN0cmluZw=='
  14. >>> base64.b64decode('YmluYXJ5AHN0cmluZw==')
  15. 'binary\x00string'
  16. 由于标准的Base64编码后可能出现字符+和/,在URL中就不能直接作为参数,所以又有一种"url safe"的base64编码,其实就是把字符+和/分别变成-和_:
  17. >>> base64.b64encode('i\xb7\x1d\xfb\xef\xff')
  18. 'abcd++//'
  19. >>> base64.urlsafe_b64encode('i\xb7\x1d\xfb\xef\xff')
  20. 'abcd--__'
  21. >>> base64.urlsafe_b64decode('abcd--__')
  22. 'i\xb7\x1d\xfb\xef\xff'
  23. 还可以自己定义64个字符的排列顺序,这样就可以自定义Base64编码,不过,通常情况下完全没有必要。
  24. Base64是一种通过查表的编码方法,不能用于加密,即使使用自定义的编码表也不行。
  25. Base64适用于小段内容的编码,比如数字证书签名、Cookie的内容等。
  26. 由于=字符也可能出现在Base64编码中,但=用在URL、Cookie里面会造成歧义,所以,很多Base64编码后会把=去掉:
  27. # 标准Base64:
  28. 'abcd' -> 'YWJjZA=='
  29. # 自动去掉=:
  30. 'abcd' -> 'YWJjZA'
  31. 去掉=后怎么解码呢?因为Base64是把3个字节变为4个字节,所以,Base64编码的长度永远是4的倍数,因此,需要加上=把Base64字符串的长度变为4的倍数,就可以正常解码了。
  32. 请写一个能处理去掉=的base64解码函数:
  33. >>> base64.b64decode('YWJjZA==')
  34. 'abcd'
  35. >>> base64.b64decode('YWJjZA')
  36. Traceback (most recent call last):
  37. ...
  38. TypeError: Incorrect padding
  39. >>> safe_b64decode('YWJjZA')
  40. 'abcd'


实现代码

  1. /**
  2. * BASE64转换工具
  3. *
  4. */
  5. public class Base64Util {
  6. private static final char intToBase64[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
  7. 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
  8. 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  9. 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
  10. private static final byte base64ToInt[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  11. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  12. -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
  13. -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
  14. 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32,
  15. 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 };
  16. /**
  17. * byte数组转换成BASE64字符串
  18. *
  19. * @param data byte数组
  20. * @return <b>String</b> BASE64字符串<b><br/>null</b> 转换失败
  21. */
  22. public static String byteArrayToBase64(byte[] data) {
  23. if(data==null || data.length==0){
  24. return null;
  25. }
  26. int len = data.length;
  27. int groups = len/3;
  28. int nogroups = len-3*groups;
  29. int resultLen = (len+2)/3*4;
  30. StringBuffer result = new StringBuffer(resultLen);
  31. int cursor = 0;
  32. for(int i=0;i<groups;i++){
  33. int byte0 = data[cursor++]&0xff;
  34. int byte1 = data[cursor++]&0xff;
  35. int byte2 = data[cursor++]&0xff;
  36. result.append(intToBase64[byte0>>2]);
  37. result.append(intToBase64[(byte0<<4)&0x3f|(byte1>>4)]);
  38. result.append(intToBase64[(byte1<<2)&0x3f|(byte2>>6)]);
  39. result.append(intToBase64[byte2&0x3f]);
  40. }
  41. if(nogroups!=0){
  42. int byte0 = data[cursor++]&0xff;
  43. result.append(intToBase64[byte0>>2]);
  44. if(nogroups==1){
  45. result.append(intToBase64[(byte0<<4)&0x3f]);
  46. result.append("==");
  47. }else{
  48. int byte1 = data[cursor++]&0xff;
  49. result.append(intToBase64[(byte0<<4)&0x3f|(byte1>>4)]);
  50. result.append(intToBase64[(byte1<<2)&0x3f]);
  51. result.append('=');
  52. }
  53. }
  54. return result.toString();
  55. }
  56. /**
  57. * BASE64字符串转换成byte数组
  58. *
  59. * @param data BASE64字符串
  60. * @return <b>String</b> byte数组<b><br/>null</b> 转换失败
  61. */
  62. public static byte[] base64ToByteArray(String data) {
  63. if(StringUtil.isEmpty(data)){
  64. return null;
  65. }
  66. int len = data.length();
  67. int groups = len/4;
  68. if(groups*4!=len){
  69. return null;
  70. }
  71. int nogroups = 0;
  72. int fullGroups = groups;
  73. if(len!=0){
  74. if(data.charAt(len-1)=='='){
  75. nogroups++;
  76. fullGroups--;
  77. }
  78. if(data.charAt(len-2)=='='){
  79. nogroups++;
  80. }
  81. }
  82. byte[] result = new byte[groups*3-nogroups];
  83. int inCursor = 0;
  84. int outCursor = 0;
  85. try {
  86. for(int i=0;i<fullGroups;i++){
  87. int ch0 = base64toInt(data.charAt(inCursor++));
  88. int ch1 = base64toInt(data.charAt(inCursor++));
  89. int ch2 = base64toInt(data.charAt(inCursor++));
  90. int ch3 = base64toInt(data.charAt(inCursor++));
  91. result[outCursor++] = (byte) ((ch0<<2)|(ch1>>4));
  92. result[outCursor++] = (byte) ((ch1<<4)|(ch2>>2));
  93. result[outCursor++] = (byte) ((ch2<<6)|ch3);
  94. }
  95. if(nogroups!=0){
  96. int ch0 = base64toInt(data.charAt(inCursor++));
  97. int ch1 = base64toInt(data.charAt(inCursor++));
  98. result[outCursor++] = (byte) ((ch0<<2)|(ch1>>4));
  99. if(nogroups==1){
  100. int ch2 = base64toInt(data.charAt(inCursor++));
  101. result[outCursor++] = (byte) ((ch1<<4)|(ch2>>2));
  102. }
  103. }
  104. } catch (Exception e) {
  105. return null;
  106. }
  107. return result;
  108. }
  109. private static int base64toInt(char c) {
  110. int result = base64ToInt[c];
  111. if(result<0){
  112. throw new RuntimeException();
  113. }
  114. return result;
  115. }
  116. }


声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号