Java Base64加密、解密原理Java代码

时间:2022-01-24 21:06:26

Java Base64加密、解密原理Java代码

Base64是什么:

Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,大家可以查看RFC2045~RFC2049,上面有MIME的详细规范。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)。
  Base64要求把每三个8Bit的字节转换为四个6Bit的字节(3*8 = 4*6 = 24),然后把6Bit再添两位高位0,组成四个8Bit的字节,也就是说,转换后的字符串理论上将要比原来的长1/3。
规则
  关于这个编码的规则:
  ①.把3个字符变成4个字符..
  ②每76个字符加一个换行符..
  ③.最后的结束符也要处理..
  这样说会不会太抽象了?不怕,我们来看一个例子:
  转换前 aaaaaabb ccccdddd eeffffff
  转换后 00aaaaaa 00bbcccc 00ddddee 00ffffff
  应该很清楚了吧?上面的三个字节是原文,下面的四个字节是转换后的Base64编码,其前两位均为0。
  转换后,我们用一个码表来得到我们想要的字符串(也就是最终的Base64编码),这个表是这样的:(摘自RFC2045)

java代码示例:

  1. public final class Base64 {
  2. static private final int BASELENGTH = 255;
  3. static private final int LOOKUPLENGTH = 64;
  4. static private final int TWENTYFOURBITGROUP = 24;
  5. static private final int EIGHTBIT = 8;
  6. static private final int SIXTEENBIT = 16;
  7. static private final int SIXBIT = 6;
  8. static private final int FOURBYTE = 4;
  9. static private final int SIGN = -128;
  10. static private final char PAD = '=';
  11. static private final boolean fDebug = false;
  12. static final private byte[] base64Alphabet = new byte[BASELENGTH];
  13. static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
  14. static {
  15. for (int i = 0; i < BASELENGTH; i++) {
  16. base64Alphabet[i] = -1;
  17. }
  18. for (int i = 'Z'; i >= 'A'; i--) {
  19. base64Alphabet[i] = (byte) (i - 'A');
  20. }
  21. for (int i = 'z'; i >= 'a'; i--) {
  22. base64Alphabet[i] = (byte) (i - 'a' + 26);
  23. }
  24. for (int i = '9'; i >= '0'; i--) {
  25. base64Alphabet[i] = (byte) (i - '0' + 52);
  26. }
  27. base64Alphabet['+'] = 62;
  28. base64Alphabet['/'] = 63;
  29. for (int i = 0; i <= 25; i++)
  30. lookUpBase64Alphabet[i] = (char) ('A' + i);
  31. for (int i = 26, j = 0; i <= 51; i++, j++)
  32. lookUpBase64Alphabet[i] = (char) ('a' + j);
  33. for (int i = 52, j = 0; i <= 61; i++, j++)
  34. lookUpBase64Alphabet[i] = (char) ('0' + j);
  35. lookUpBase64Alphabet[62] = (char) '+';
  36. lookUpBase64Alphabet[63] = (char) '/';
  37. }
  38. protected static boolean isWhiteSpace(char octect) {
  39. return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
  40. }
  41. protected static boolean isPad(char octect) {
  42. return (octect == PAD);
  43. }
  44. protected static boolean isData(char octect) {
  45. return (base64Alphabet[octect] != -1);
  46. }
  47. protected static boolean isBase64(char octect) {
  48. return (isWhiteSpace(octect) || isPad(octect) || isData(octect));
  49. }
  50. /**
  51. * Encodes hex octects into Base64
  52. *
  53. * @param binaryData
  54. *            Array containing binaryData
  55. * @return Encoded Base64 array
  56. */
  57. public static String encode(byte[] binaryData) {
  58. if (binaryData == null)
  59. return null;
  60. int lengthDataBits = binaryData.length * EIGHTBIT;
  61. if (lengthDataBits == 0) {
  62. return "";
  63. }
  64. int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
  65. int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
  66. int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1
  67. : numberTriplets;
  68. int numberLines = (numberQuartet - 1) / 19 + 1;
  69. char encodedData[] = null;
  70. encodedData = new char[numberQuartet * 4 + numberLines];
  71. byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
  72. int encodedIndex = 0;
  73. int dataIndex = 0;
  74. int i = 0;
  75. if (fDebug) {
  76. System.out.println("number of triplets = " + numberTriplets);
  77. }
  78. for (int line = 0; line < numberLines - 1; line++) {
  79. for (int quartet = 0; quartet < 19; quartet++) {
  80. b1 = binaryData[dataIndex++];
  81. b2 = binaryData[dataIndex++];
  82. b3 = binaryData[dataIndex++];
  83. if (fDebug) {
  84. System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= "
  85. + b3);
  86. }
  87. l = (byte) (b2 & 0x0f);
  88. k = (byte) (b1 & 0x03);
  89. byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
  90. : (byte) ((b1) >> 2 ^ 0xc0);
  91. byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
  92. : (byte) ((b2) >> 4 ^ 0xf0);
  93. byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6)
  94. : (byte) ((b3) >> 6 ^ 0xfc);
  95. if (fDebug) {
  96. System.out.println("val2 = " + val2);
  97. System.out.println("k4 = " + (k << 4));
  98. System.out.println("vak = " + (val2 | (k << 4)));
  99. }
  100. encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
  101. encodedData[encodedIndex++] = lookUpBase64Alphabet[val2
  102. | (k << 4)];
  103. encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2)
  104. | val3];
  105. encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
  106. i++;
  107. }
  108. encodedData[encodedIndex++] = 0xa;
  109. }
  110. for (; i < numberTriplets; i++) {
  111. b1 = binaryData[dataIndex++];
  112. b2 = binaryData[dataIndex++];
  113. b3 = binaryData[dataIndex++];
  114. if (fDebug) {
  115. System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3);
  116. }
  117. l = (byte) (b2 & 0x0f);
  118. k = (byte) (b1 & 0x03);
  119. byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
  120. : (byte) ((b1) >> 2 ^ 0xc0);
  121. byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
  122. : (byte) ((b2) >> 4 ^ 0xf0);
  123. byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6)
  124. : (byte) ((b3) >> 6 ^ 0xfc);
  125. if (fDebug) {
  126. System.out.println("val2 = " + val2);
  127. System.out.println("k4 = " + (k << 4));
  128. System.out.println("vak = " + (val2 | (k << 4)));
  129. }
  130. encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
  131. encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
  132. encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
  133. encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
  134. }
  135. // form integral number of 6-bit groups
  136. if (fewerThan24bits == EIGHTBIT) {
  137. b1 = binaryData[dataIndex];
  138. k = (byte) (b1 & 0x03);
  139. if (fDebug) {
  140. System.out.println("b1=" + b1);
  141. System.out.println("b1<<2 = " + (b1 >> 2));
  142. }
  143. byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
  144. : (byte) ((b1) >> 2 ^ 0xc0);
  145. encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
  146. encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
  147. encodedData[encodedIndex++] = PAD;
  148. encodedData[encodedIndex++] = PAD;
  149. } else if (fewerThan24bits == SIXTEENBIT) {
  150. b1 = binaryData[dataIndex];
  151. b2 = binaryData[dataIndex + 1];
  152. l = (byte) (b2 & 0x0f);
  153. k = (byte) (b1 & 0x03);
  154. byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
  155. : (byte) ((b1) >> 2 ^ 0xc0);
  156. byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
  157. : (byte) ((b2) >> 4 ^ 0xf0);
  158. encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
  159. encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
  160. encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
  161. encodedData[encodedIndex++] = PAD;
  162. }
  163. encodedData[encodedIndex] = 0xa;
  164. return new String(encodedData);
  165. }
  166. /**
  167. * Decodes Base64 data into octects
  168. *
  169. * @param binaryData
  170. *            Byte array containing Base64 data
  171. * @return Array containind decoded data.
  172. */
  173. public static byte[] decode(String encoded) {
  174. if (encoded == null)
  175. return null;
  176. char[] base64Data = encoded.toCharArray();
  177. // remove white spaces
  178. int len = removeWhiteSpace(base64Data);
  179. if (len % FOURBYTE != 0) {
  180. return null;// should be divisible by four
  181. }
  182. int numberQuadruple = (len / FOURBYTE);
  183. if (numberQuadruple == 0)
  184. return new byte[0];
  185. byte decodedData[] = null;
  186. byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;
  187. char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
  188. int i = 0;
  189. int encodedIndex = 0;
  190. int dataIndex = 0;
  191. decodedData = new byte[(numberQuadruple) * 3];
  192. for (; i < numberQuadruple - 1; i++) {
  193. if (!isData((d1 = base64Data[dataIndex++]))
  194. || !isData((d2 = base64Data[dataIndex++]))
  195. || !isData((d3 = base64Data[dataIndex++]))
  196. || !isData((d4 = base64Data[dataIndex++])))
  197. return null;// if found "no data" just return null
  198. b1 = base64Alphabet[d1];
  199. b2 = base64Alphabet[d2];
  200. b3 = base64Alphabet[d3];
  201. b4 = base64Alphabet[d4];
  202. decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
  203. decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
  204. decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
  205. }
  206. if (!isData((d1 = base64Data[dataIndex++]))
  207. || !isData((d2 = base64Data[dataIndex++]))) {
  208. return null;// if found "no data" just return null
  209. }
  210. b1 = base64Alphabet[d1];
  211. b2 = base64Alphabet[d2];
  212. d3 = base64Data[dataIndex++];
  213. d4 = base64Data[dataIndex++];
  214. if (!isData((d3)) || !isData((d4))) {// Check if they are PAD characters
  215. if (isPad(d3) && isPad(d4)) { // Two PAD e.g. 3c[Pad][Pad]
  216. if ((b2 & 0xf) != 0)// last 4 bits should be zero
  217. return null;
  218. byte[] tmp = new byte[i * 3 + 1];
  219. System.arraycopy(decodedData, 0, tmp, 0, i * 3);
  220. tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
  221. return tmp;
  222. } else if (!isPad(d3) && isPad(d4)) { // One PAD e.g. 3cQ[Pad]
  223. b3 = base64Alphabet[d3];
  224. if ((b3 & 0x3) != 0)// last 2 bits should be zero
  225. return null;
  226. byte[] tmp = new byte[i * 3 + 2];
  227. System.arraycopy(decodedData, 0, tmp, 0, i * 3);
  228. tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
  229. tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
  230. return tmp;
  231. } else {
  232. return null;// an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX"
  233. // where X is non data
  234. }
  235. } else { // No PAD e.g 3cQl
  236. b3 = base64Alphabet[d3];
  237. b4 = base64Alphabet[d4];
  238. decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
  239. decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
  240. decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
  241. }
  242. return decodedData;
  243. }
  244. /**
  245. * remove WhiteSpace from MIME containing encoded Base64 data.
  246. *
  247. * @param data
  248. *            the byte array of base64 data (with WS)
  249. * @return the new length
  250. */
  251. protected static int removeWhiteSpace(char[] data) {
  252. if (data == null)
  253. return 0;
  254. // count characters that's not whitespace
  255. int newSize = 0;
  256. int len = data.length;
  257. for (int i = 0; i < len; i++) {
  258. if (!isWhiteSpace(data[i]))
  259. data[newSize++] = data[i];
  260. }
  261. return newSize;
  262. }
  263. public static void main(String[] args) {
  264. System.out.println(encode("*".getBytes()));
  265. }
  266. }