9cd3d4d653498371a6ef85413dc6c94c2f509857.svn-base 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  1. package com.chinacreator.process.util;
  2. import java.io.UnsupportedEncodingException;
  3. import java.util.Arrays;
  4. public class Base64 extends BaseNCodec {
  5. /**
  6. * BASE32 characters are 6 bits in length. They are formed by taking a block
  7. * of 3 octets to form a 24-bit string, which is converted into 4 BASE64
  8. * characters.
  9. */
  10. private static final int BITS_PER_ENCODED_BYTE = 6;
  11. private static final int BYTES_PER_UNENCODED_BLOCK = 3;
  12. private static final int BYTES_PER_ENCODED_BLOCK = 4;
  13. /**
  14. * Chunk separator per RFC 2045 section 2.1.
  15. *
  16. * <p>
  17. * N.B. The next major release may break compatibility and make this field
  18. * private.
  19. * </p>
  20. */
  21. static final byte[] CHUNK_SEPARATOR = { '\r', '\n' };
  22. /**
  23. * This array is a lookup table that translates 6-bit positive integer index
  24. * values into their "Base64 Alphabet" equivalents as specified in Table 1
  25. * of RFC 2045.
  26. */
  27. private static final byte[] STANDARD_ENCODE_TABLE = { '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', '+', '/' };
  28. /**
  29. * This is a copy of the STANDARD_ENCODE_TABLE above, but with + and /
  30. * changed to - and _ to make the encoded Base64 results more URL-SAFE. This
  31. * table is only used when the Base64's mode is set to URL-SAFE.
  32. */
  33. private static final byte[] URL_SAFE_ENCODE_TABLE = { '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', '-', '_' };
  34. /**
  35. * This array is a lookup table that translates Unicode characters drawn
  36. * from the "Base64 Alphabet" (as specified in Table 1 of RFC 2045) into
  37. * their 6-bit positive integer equivalents. Characters that are not in the
  38. * Base64 alphabet but fall within the bounds of the array are translated to
  39. * -1.
  40. *
  41. * Note: '+' and '-' both decode to 62. '/' and '_' both decode to 63. This
  42. * means decoder seamlessly handles both URL_SAFE and STANDARD base64. (The
  43. * encoder, on the other hand, needs to know ahead of time what to emit).
  44. *
  45. */
  46. private static final byte[] DECODE_TABLE = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
  47. 44, 45, 46, 47, 48, 49, 50, 51 };
  48. /**
  49. * Base64 uses 6-bit fields.
  50. */
  51. /** Mask used to extract 6 bits, used when encoding */
  52. private static final int MASK_6BITS = 0x3f;
  53. // The static final fields above are used for the original static byte[]
  54. // methods on Base64.
  55. // The private member fields below are used with the new streaming approach,
  56. // which requires
  57. // some state be preserved between calls of encode() and decode().
  58. /**
  59. * Encode table to use: either STANDARD or URL_SAFE. Note: the DECODE_TABLE
  60. * above remains static because it is able to decode both STANDARD and
  61. * URL_SAFE streams, but the encodeTable must be a member variable so we can
  62. * switch between the two modes.
  63. */
  64. private final byte[] encodeTable;
  65. // Only one decode table currently; keep for consistency with Base32 code
  66. private final byte[] decodeTable = DECODE_TABLE;
  67. /**
  68. * Line separator for encoding. Not used when decoding. Only used if
  69. * lineLength > 0.
  70. */
  71. private final byte[] lineSeparator;
  72. /**
  73. * Convenience variable to help us determine when our buffer is going to run
  74. * out of room and needs resizing.
  75. * <code>decodeSize = 3 + lineSeparator.length;</code>
  76. */
  77. private final int decodeSize;
  78. /**
  79. * Convenience variable to help us determine when our buffer is going to run
  80. * out of room and needs resizing.
  81. * <code>encodeSize = 4 + lineSeparator.length;</code>
  82. */
  83. private final int encodeSize;
  84. /**
  85. * Creates a Base64 codec used for decoding (all modes) and encoding in
  86. * URL-unsafe mode.
  87. * <p>
  88. * When encoding the line length is 0 (no chunking), and the encoding table
  89. * is STANDARD_ENCODE_TABLE.
  90. * </p>
  91. *
  92. * <p>
  93. * When decoding all variants are supported.
  94. * </p>
  95. */
  96. public Base64() {
  97. this(0);
  98. }
  99. /**
  100. * Creates a Base64 codec used for decoding (all modes) and encoding in the
  101. * given URL-safe mode.
  102. * <p>
  103. * When encoding the line length is 76, the line separator is CRLF, and the
  104. * encoding table is STANDARD_ENCODE_TABLE.
  105. * </p>
  106. *
  107. * <p>
  108. * When decoding all variants are supported.
  109. * </p>
  110. *
  111. * @param urlSafe
  112. * if {@code true}, URL-safe encoding is used. In most cases this
  113. * should be set to {@code false}.
  114. * @since 1.4
  115. */
  116. public Base64(final boolean urlSafe) {
  117. this(MIME_CHUNK_SIZE, CHUNK_SEPARATOR, urlSafe);
  118. }
  119. /**
  120. * Creates a Base64 codec used for decoding (all modes) and encoding in
  121. * URL-unsafe mode.
  122. * <p>
  123. * When encoding the line length is given in the constructor, the line
  124. * separator is CRLF, and the encoding table is STANDARD_ENCODE_TABLE.
  125. * </p>
  126. * <p>
  127. * Line lengths that aren't multiples of 4 will still essentially end up
  128. * being multiples of 4 in the encoded data.
  129. * </p>
  130. * <p>
  131. * When decoding all variants are supported.
  132. * </p>
  133. *
  134. * @param lineLength
  135. * Each line of encoded data will be at most of the given length
  136. * (rounded down to nearest multiple of 4). If lineLength <= 0,
  137. * then the output will not be divided into lines (chunks).
  138. * Ignored when decoding.
  139. */
  140. public Base64(final int lineLength) {
  141. this(lineLength, CHUNK_SEPARATOR);
  142. }
  143. /**
  144. * Creates a Base64 codec used for decoding (all modes) and encoding in
  145. * URL-unsafe mode.
  146. * <p>
  147. * When encoding the line length and line separator are given in the
  148. * constructor, and the encoding table is STANDARD_ENCODE_TABLE.
  149. * </p>
  150. * <p>
  151. * Line lengths that aren't multiples of 4 will still essentially end up
  152. * being multiples of 4 in the encoded data.
  153. * </p>
  154. * <p>
  155. * When decoding all variants are supported.
  156. * </p>
  157. *
  158. * @param lineLength
  159. * Each line of encoded data will be at most of the given length
  160. * (rounded down to nearest multiple of 4). If lineLength <= 0,
  161. * then the output will not be divided into lines (chunks).
  162. * Ignored when decoding.
  163. * @param lineSeparator
  164. * Each line of encoded data will end with this sequence of
  165. * bytes.
  166. * @throws IllegalArgumentException
  167. * Thrown when the provided lineSeparator included some base64
  168. * characters.
  169. */
  170. public Base64(final int lineLength, final byte[] lineSeparator) {
  171. this(lineLength, lineSeparator, false);
  172. }
  173. /**
  174. * Creates a Base64 codec used for decoding (all modes) and encoding in
  175. * URL-unsafe mode.
  176. * <p>
  177. * When encoding the line length and line separator are given in the
  178. * constructor, and the encoding table is STANDARD_ENCODE_TABLE.
  179. * </p>
  180. * <p>
  181. * Line lengths that aren't multiples of 4 will still essentially end up
  182. * being multiples of 4 in the encoded data.
  183. * </p>
  184. * <p>
  185. * When decoding all variants are supported.
  186. * </p>
  187. *
  188. * @param lineLength
  189. * Each line of encoded data will be at most of the given length
  190. * (rounded down to nearest multiple of 4). If lineLength <= 0,
  191. * then the output will not be divided into lines (chunks).
  192. * Ignored when decoding.
  193. * @param lineSeparator
  194. * Each line of encoded data will end with this sequence of
  195. * bytes.
  196. * @param urlSafe
  197. * Instead of emitting '+' and '/' we emit '-' and '_'
  198. * respectively. urlSafe is only applied to encode operations.
  199. * Decoding seamlessly handles both modes. <b>Note: no padding is
  200. * added when using the URL-safe alphabet.</b>
  201. * @throws IllegalArgumentException
  202. * The provided lineSeparator included some base64 characters.
  203. * That's not going to work!
  204. */
  205. public Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe) {
  206. super(BYTES_PER_UNENCODED_BLOCK, BYTES_PER_ENCODED_BLOCK, lineLength, lineSeparator == null ? 0 : lineSeparator.length);
  207. // TODO could be simplified if there is no requirement to reject invalid
  208. // line sep when length <=0
  209. // @see test case Base64Test.testConstructors()
  210. if (lineSeparator != null) {
  211. if (containsAlphabetOrPad(lineSeparator)) {
  212. try {
  213. final String sep = new String(lineSeparator, "UTF-8");
  214. throw new IllegalArgumentException("lineSeparator must not contain base64 characters: [" + sep + "]");
  215. } catch (UnsupportedEncodingException e) {
  216. e.printStackTrace();
  217. }
  218. }
  219. if (lineLength > 0) { // null line-sep forces no chunking rather
  220. // than throwing IAE
  221. this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length;
  222. this.lineSeparator = new byte[lineSeparator.length];
  223. System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length);
  224. } else {
  225. this.encodeSize = BYTES_PER_ENCODED_BLOCK;
  226. this.lineSeparator = null;
  227. }
  228. } else {
  229. this.encodeSize = BYTES_PER_ENCODED_BLOCK;
  230. this.lineSeparator = null;
  231. }
  232. this.decodeSize = this.encodeSize - 1;
  233. this.encodeTable = urlSafe ? URL_SAFE_ENCODE_TABLE : STANDARD_ENCODE_TABLE;
  234. }
  235. @Override
  236. public String encodeToString(byte[] pArray) throws UnsupportedEncodingException {
  237. return super.encodeToString(pArray);
  238. }
  239. /**
  240. * <p>
  241. * Encodes all of the provided data, starting at inPos, for inAvail bytes.
  242. * Must be called at least twice: once with the data to encode, and once
  243. * with inAvail set to "-1" to alert encoder that EOF has been reached, to
  244. * flush last remaining bytes (if not multiple of 3).
  245. * </p>
  246. * <p>
  247. * <b>Note: no padding is added when encoding using the URL-safe
  248. * alphabet.</b>
  249. * </p>
  250. *
  251. * @param in
  252. * byte[] array of binary data to base64 encode.
  253. * @param inPos
  254. * Position to start reading data from.
  255. * @param inAvail
  256. * Amount of bytes available from input for encoding.
  257. * @param context
  258. * the context to be used
  259. */
  260. @Override
  261. void encode(final byte[] in, int inPos, final int inAvail, final Context context) {
  262. if (context.eof) {
  263. return;
  264. }
  265. // inAvail < 0 is how we're informed of EOF in the underlying data we're
  266. // encoding.
  267. if (inAvail < 0) {
  268. context.eof = true;
  269. if (0 == context.modulus && lineLength == 0) {
  270. return; // no leftovers to process and not using chunking
  271. }
  272. final byte[] buffer = ensureBufferSize(encodeSize, context);
  273. final int savedPos = context.pos;
  274. switch (context.modulus) { // 0-2
  275. case 0: // nothing to do here
  276. break;
  277. case 1: // 8 bits = 6 + 2
  278. // top 6 bits:
  279. buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 2) & MASK_6BITS];
  280. // remaining 2:
  281. buffer[context.pos++] = encodeTable[(context.ibitWorkArea << 4) & MASK_6BITS];
  282. // URL-SAFE skips the padding to further reduce size.
  283. if (encodeTable == STANDARD_ENCODE_TABLE) {
  284. buffer[context.pos++] = PAD;
  285. buffer[context.pos++] = PAD;
  286. }
  287. break;
  288. case 2: // 16 bits = 6 + 6 + 4
  289. buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 10) & MASK_6BITS];
  290. buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 4) & MASK_6BITS];
  291. buffer[context.pos++] = encodeTable[(context.ibitWorkArea << 2) & MASK_6BITS];
  292. // URL-SAFE skips the padding to further reduce size.
  293. if (encodeTable == STANDARD_ENCODE_TABLE) {
  294. buffer[context.pos++] = PAD;
  295. }
  296. break;
  297. default:
  298. throw new IllegalStateException("Impossible modulus " + context.modulus);
  299. }
  300. context.currentLinePos += context.pos - savedPos; // keep track of
  301. // current line
  302. // position
  303. // if currentPos == 0 we are at the start of a line, so don't add
  304. // CRLF
  305. if (lineLength > 0 && context.currentLinePos > 0) {
  306. System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length);
  307. context.pos += lineSeparator.length;
  308. }
  309. } else {
  310. for (int i = 0; i < inAvail; i++) {
  311. final byte[] buffer = ensureBufferSize(encodeSize, context);
  312. context.modulus = (context.modulus + 1) % BYTES_PER_UNENCODED_BLOCK;
  313. int b = in[inPos++];
  314. if (b < 0) {
  315. b += 256;
  316. }
  317. context.ibitWorkArea = (context.ibitWorkArea << 8) + b; // BITS_PER_BYTE
  318. if (0 == context.modulus) { // 3 bytes = 24 bits = 4 * 6 bits to
  319. // extract
  320. buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 18) & MASK_6BITS];
  321. buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 12) & MASK_6BITS];
  322. buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 6) & MASK_6BITS];
  323. buffer[context.pos++] = encodeTable[context.ibitWorkArea & MASK_6BITS];
  324. context.currentLinePos += BYTES_PER_ENCODED_BLOCK;
  325. if (lineLength > 0 && lineLength <= context.currentLinePos) {
  326. System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length);
  327. context.pos += lineSeparator.length;
  328. context.currentLinePos = 0;
  329. }
  330. }
  331. }
  332. }
  333. }
  334. /**
  335. * <p>
  336. * Decodes all of the provided data, starting at inPos, for inAvail bytes.
  337. * Should be called at least twice: once with the data to decode, and once
  338. * with inAvail set to "-1" to alert decoder that EOF has been reached. The
  339. * "-1" call is not necessary when decoding, but it doesn't hurt, either.
  340. * </p>
  341. * <p>
  342. * Ignores all non-base64 characters. This is how chunked (e.g. 76
  343. * character) data is handled, since CR and LF are silently ignored, but has
  344. * implications for other bytes, too. This method subscribes to the
  345. * garbage-in, garbage-out philosophy: it will not check the provided data
  346. * for validity.
  347. * </p>
  348. *
  349. * @param in
  350. * byte[] array of ascii data to base64 decode.
  351. * @param inPos
  352. * Position to start reading data from.
  353. * @param inAvail
  354. * Amount of bytes available from input for encoding.
  355. * @param context
  356. * the context to be used
  357. */
  358. @Override
  359. void decode(final byte[] in, int inPos, final int inAvail, final Context context) {
  360. if (context.eof) {
  361. return;
  362. }
  363. if (inAvail < 0) {
  364. context.eof = true;
  365. }
  366. for (int i = 0; i < inAvail; i++) {
  367. final byte[] buffer = ensureBufferSize(decodeSize, context);
  368. final byte b = in[inPos++];
  369. if (b == PAD) {
  370. // We're done.
  371. context.eof = true;
  372. break;
  373. } else {
  374. if (b >= 0 && b < DECODE_TABLE.length) {
  375. final int result = DECODE_TABLE[b];
  376. if (result >= 0) {
  377. context.modulus = (context.modulus + 1) % BYTES_PER_ENCODED_BLOCK;
  378. context.ibitWorkArea = (context.ibitWorkArea << BITS_PER_ENCODED_BYTE) + result;
  379. if (context.modulus == 0) {
  380. buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 16) & MASK_8BITS);
  381. buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 8) & MASK_8BITS);
  382. buffer[context.pos++] = (byte) (context.ibitWorkArea & MASK_8BITS);
  383. }
  384. }
  385. }
  386. }
  387. }
  388. // Two forms of EOF as far as base64 decoder is concerned: actual
  389. // EOF (-1) and first time '=' character is encountered in stream.
  390. // This approach makes the '=' padding characters completely optional.
  391. if (context.eof && context.modulus != 0) {
  392. final byte[] buffer = ensureBufferSize(decodeSize, context);
  393. // We have some spare bits remaining
  394. // Output all whole multiples of 8 bits and ignore the rest
  395. switch (context.modulus) {
  396. // case 0 : // impossible, as excluded above
  397. case 1: // 6 bits - ignore entirely
  398. // TODO not currently tested; perhaps it is impossible?
  399. break;
  400. case 2: // 12 bits = 8 + 4
  401. context.ibitWorkArea = context.ibitWorkArea >> 4; // dump the
  402. // extra 4
  403. // bits
  404. buffer[context.pos++] = (byte) ((context.ibitWorkArea) & MASK_8BITS);
  405. break;
  406. case 3: // 18 bits = 8 + 8 + 2
  407. context.ibitWorkArea = context.ibitWorkArea >> 2; // dump 2 bits
  408. buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 8) & MASK_8BITS);
  409. buffer[context.pos++] = (byte) ((context.ibitWorkArea) & MASK_8BITS);
  410. break;
  411. default:
  412. throw new IllegalStateException("Impossible modulus " + context.modulus);
  413. }
  414. }
  415. }
  416. /**
  417. * Encodes binary data using the base64 algorithm but does not chunk the
  418. * output.
  419. *
  420. * @param binaryData
  421. * binary data to encode
  422. * @return byte[] containing Base64 characters in their UTF-8
  423. * representation.
  424. */
  425. public static byte[] encodeBase64(final byte[] binaryData) {
  426. return encodeBase64(binaryData, false);
  427. }
  428. /**
  429. * Encodes binary data using the base64 algorithm but does not chunk the
  430. * output.
  431. *
  432. * NOTE: We changed the behaviour of this method from multi-line chunking
  433. *
  434. * @param binaryData
  435. * binary data to encode
  436. * @return String containing Base64 characters.
  437. * @throws UnsupportedEncodingException
  438. */
  439. public static String encodeBase64String(final byte[] binaryData) throws UnsupportedEncodingException {
  440. return new String(encodeBase64(binaryData, false), "UTF-8");
  441. }
  442. /**
  443. * Encodes binary data using a URL-safe variation of the base64 algorithm
  444. * but does not chunk the output. The url-safe variation emits - and _
  445. * instead of + and / characters. <b>Note: no padding is added.</b>
  446. *
  447. * @param binaryData
  448. * binary data to encode
  449. * @return byte[] containing Base64 characters in their UTF-8
  450. * representation.
  451. */
  452. public static byte[] encodeBase64URLSafe(final byte[] binaryData) {
  453. return encodeBase64(binaryData, false, true);
  454. }
  455. /**
  456. * Encodes binary data using a URL-safe variation of the base64 algorithm
  457. * but does not chunk the output. The url-safe variation emits - and _
  458. * instead of + and / characters. <b>Note: no padding is added.</b>
  459. *
  460. * @param binaryData
  461. * binary data to encode
  462. * @return String containing Base64 characters
  463. * @throws UnsupportedEncodingException
  464. */
  465. public static String encodeBase64URLSafeString(final byte[] binaryData) throws UnsupportedEncodingException {
  466. return new String(encodeBase64(binaryData, false, true), "UTF-8");
  467. }
  468. /**
  469. * Encodes binary data using the base64 algorithm and chunks the encoded
  470. * output into 76 character blocks
  471. *
  472. * @param binaryData
  473. * binary data to encode
  474. * @return Base64 characters chunked in 76 character blocks
  475. */
  476. public static byte[] encodeBase64Chunked(final byte[] binaryData) {
  477. return encodeBase64(binaryData, true);
  478. }
  479. /**
  480. * Encodes binary data using the base64 algorithm, optionally chunking the
  481. * output into 76 character blocks.
  482. *
  483. * @param binaryData
  484. * Array containing binary data to encode.
  485. * @param isChunked
  486. * if {@code true} this encoder will chunk the base64 output into
  487. * 76 character blocks
  488. * @return Base64-encoded data.
  489. * @throws IllegalArgumentException
  490. * Thrown when the input array needs an output array bigger than
  491. * {@link Integer#MAX_VALUE}
  492. */
  493. public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked) {
  494. return encodeBase64(binaryData, isChunked, false);
  495. }
  496. /**
  497. * Encodes binary data using the base64 algorithm, optionally chunking the
  498. * output into 76 character blocks.
  499. *
  500. * @param binaryData
  501. * Array containing binary data to encode.
  502. * @param isChunked
  503. * if {@code true} this encoder will chunk the base64 output into
  504. * 76 character blocks
  505. * @param urlSafe
  506. * if {@code true} this encoder will emit - and _ instead of the
  507. * usual + and / characters. <b>Note: no padding is added when
  508. * encoding using the URL-safe alphabet.</b>
  509. * @return Base64-encoded data.
  510. * @throws IllegalArgumentException
  511. * Thrown when the input array needs an output array bigger than
  512. * {@link Integer#MAX_VALUE}
  513. */
  514. public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe) {
  515. return encodeBase64(binaryData, isChunked, urlSafe, Integer.MAX_VALUE);
  516. }
  517. /**
  518. * Encodes binary data using the base64 algorithm, optionally chunking the
  519. * output into 76 character blocks.
  520. *
  521. * @param binaryData
  522. * Array containing binary data to encode.
  523. * @param isChunked
  524. * if {@code true} this encoder will chunk the base64 output into
  525. * 76 character blocks
  526. * @param urlSafe
  527. * if {@code true} this encoder will emit - and _ instead of the
  528. * usual + and / characters. <b>Note: no padding is added when
  529. * encoding using the URL-safe alphabet.</b>
  530. * @param maxResultSize
  531. * The maximum result size to accept.
  532. * @return Base64-encoded data.
  533. * @throws IllegalArgumentException
  534. * Thrown when the input array needs an output array bigger than
  535. * maxResultSize
  536. */
  537. public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize) {
  538. if (binaryData == null || binaryData.length == 0) {
  539. return binaryData;
  540. }
  541. // Create this so can use the super-class method
  542. // Also ensures that the same roundings are performed by the ctor and
  543. // the code
  544. final Base64 b64 = isChunked ? new Base64(urlSafe) : new Base64(0, CHUNK_SEPARATOR, urlSafe);
  545. final long len = b64.getEncodedLength(binaryData);
  546. if (len > maxResultSize) {
  547. throw new IllegalArgumentException("Input array too big, the output array would be bigger (" + len + ") than the specified maximum size of " + maxResultSize);
  548. }
  549. return b64.encode(binaryData);
  550. }
  551. /**
  552. * Decodes a Base64 String into octets
  553. *
  554. * @param base64String
  555. * String containing Base64 data
  556. * @return Array containing decoded data.
  557. * @throws UnsupportedEncodingException
  558. */
  559. public static byte[] decodeBase64(final String base64String) throws UnsupportedEncodingException {
  560. return new Base64().decode(base64String);
  561. }
  562. /**
  563. * Decodes Base64 data into octets
  564. *
  565. * @param base64Data
  566. * Byte array containing Base64 data
  567. * @return Array containing decoded data.
  568. */
  569. public static byte[] decodeBase64(final byte[] base64Data) {
  570. return new Base64().decode(base64Data);
  571. }
  572. /**
  573. * Returns whether or not the <code>octet</code> is in the Base64 alphabet.
  574. *
  575. * @param octet
  576. * The value to test
  577. * @return {@code true} if the value is defined in the the Base64 alphabet
  578. * {@code false} otherwise.
  579. */
  580. @Override
  581. protected boolean isInAlphabet(final byte octet) {
  582. return octet >= 0 && octet < decodeTable.length && decodeTable[octet] != -1;
  583. }
  584. }
  585. abstract class BaseNCodec {
  586. static class Context {
  587. /**
  588. * Place holder for the bytes we're dealing with for our based logic.
  589. * Bitwise operations store and extract the encoding or decoding from this variable.
  590. */
  591. int ibitWorkArea;
  592. /**
  593. * Place holder for the bytes we're dealing with for our based logic.
  594. * Bitwise operations store and extract the encoding or decoding from this variable.
  595. */
  596. long lbitWorkArea;
  597. /**
  598. * Buffer for streaming.
  599. */
  600. byte[] buffer;
  601. /**
  602. * Position where next character should be written in the buffer.
  603. */
  604. int pos;
  605. /**
  606. * Position where next character should be read from the buffer.
  607. */
  608. int readPos;
  609. /**
  610. * Boolean flag to indicate the EOF has been reached. Once EOF has been reached, this object becomes useless,
  611. * and must be thrown away.
  612. */
  613. boolean eof;
  614. /**
  615. * Variable tracks how many characters have been written to the current line. Only used when encoding. We use
  616. * it to make sure each encoded line never goes beyond lineLength (if lineLength > 0).
  617. */
  618. int currentLinePos;
  619. /**
  620. * Writes to the buffer only occur after every 3/5 reads when encoding, and every 4/8 reads when decoding. This
  621. * variable helps track that.
  622. */
  623. int modulus;
  624. Context() {
  625. }
  626. /**
  627. * Returns a String useful for debugging (especially within a debugger.)
  628. *
  629. * @return a String useful for debugging.
  630. */
  631. @SuppressWarnings("boxing") // OK to ignore boxing here
  632. @Override
  633. public String toString() {
  634. return String.format("%s[buffer=%s, currentLinePos=%s, eof=%s, ibitWorkArea=%s, lbitWorkArea=%s, " +
  635. "modulus=%s, pos=%s, readPos=%s]", this.getClass().getSimpleName(), Arrays.toString(buffer),
  636. currentLinePos, eof, ibitWorkArea, lbitWorkArea, modulus, pos, readPos);
  637. }
  638. }
  639. /**
  640. * EOF
  641. */
  642. static final int EOF = -1;
  643. /**
  644. * MIME chunk size per RFC 2045 section 6.8.
  645. */
  646. public static final int MIME_CHUNK_SIZE = 76;
  647. /**
  648. * PEM chunk size per RFC 1421 section 4.3.2.4.
  649. */
  650. public static final int PEM_CHUNK_SIZE = 64;
  651. private static final int DEFAULT_BUFFER_RESIZE_FACTOR = 2;
  652. /**
  653. * Defines the default buffer size - currently {@value}
  654. * - must be large enough for at least one encoded block+separator
  655. */
  656. private static final int DEFAULT_BUFFER_SIZE = 8192;
  657. /** Mask used to extract 8 bits, used in decoding bytes */
  658. protected static final int MASK_8BITS = 0xff;
  659. /**
  660. * Byte used to pad output.
  661. */
  662. protected static final byte PAD_DEFAULT = '='; // Allow static access to default
  663. protected final byte PAD = PAD_DEFAULT; // instance variable just in case it needs to vary later
  664. /** Number of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32 */
  665. private final int unencodedBlockSize;
  666. /** Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32 */
  667. private final int encodedBlockSize;
  668. /**
  669. * Chunksize for encoding. Not used when decoding.
  670. * A value of zero or less implies no chunking of the encoded data.
  671. * Rounded down to nearest multiple of encodedBlockSize.
  672. */
  673. protected final int lineLength;
  674. /**
  675. * Size of chunk separator. Not used unless {@link #lineLength} > 0.
  676. */
  677. private final int chunkSeparatorLength;
  678. /**
  679. * Note <code>lineLength</code> is rounded down to the nearest multiple of {@link #encodedBlockSize}
  680. * If <code>chunkSeparatorLength</code> is zero, then chunking is disabled.
  681. * @param unencodedBlockSize the size of an unencoded block (e.g. Base64 = 3)
  682. * @param encodedBlockSize the size of an encoded block (e.g. Base64 = 4)
  683. * @param lineLength if &gt; 0, use chunking with a length <code>lineLength</code>
  684. * @param chunkSeparatorLength the chunk separator length, if relevant
  685. */
  686. protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize,
  687. final int lineLength, final int chunkSeparatorLength) {
  688. this.unencodedBlockSize = unencodedBlockSize;
  689. this.encodedBlockSize = encodedBlockSize;
  690. final boolean useChunking = lineLength > 0 && chunkSeparatorLength > 0;
  691. this.lineLength = useChunking ? (lineLength / encodedBlockSize) * encodedBlockSize : 0;
  692. this.chunkSeparatorLength = chunkSeparatorLength;
  693. }
  694. /**
  695. * Returns true if this object has buffered data for reading.
  696. *
  697. * @param context the context to be used
  698. * @return true if there is data still available for reading.
  699. */
  700. boolean hasData(final Context context) { // package protected for access from I/O streams
  701. return context.buffer != null;
  702. }
  703. /**
  704. * Returns the amount of buffered data available for reading.
  705. *
  706. * @param context the context to be used
  707. * @return The amount of buffered data available for reading.
  708. */
  709. int available(final Context context) { // package protected for access from I/O streams
  710. return context.buffer != null ? context.pos - context.readPos : 0;
  711. }
  712. /**
  713. * Get the default buffer size. Can be overridden.
  714. *
  715. * @return {@link #DEFAULT_BUFFER_SIZE}
  716. */
  717. protected int getDefaultBufferSize() {
  718. return DEFAULT_BUFFER_SIZE;
  719. }
  720. /**
  721. * Increases our buffer by the {@link #DEFAULT_BUFFER_RESIZE_FACTOR}.
  722. * @param context the context to be used
  723. */
  724. private byte[] resizeBuffer(final Context context) {
  725. if (context.buffer == null) {
  726. context.buffer = new byte[getDefaultBufferSize()];
  727. context.pos = 0;
  728. context.readPos = 0;
  729. } else {
  730. final byte[] b = new byte[context.buffer.length * DEFAULT_BUFFER_RESIZE_FACTOR];
  731. System.arraycopy(context.buffer, 0, b, 0, context.buffer.length);
  732. context.buffer = b;
  733. }
  734. return context.buffer;
  735. }
  736. /**
  737. * Ensure that the buffer has room for <code>size</code> bytes
  738. *
  739. * @param size minimum spare space required
  740. * @param context the context to be used
  741. */
  742. protected byte[] ensureBufferSize(final int size, final Context context){
  743. if ((context.buffer == null) || (context.buffer.length < context.pos + size)){
  744. return resizeBuffer(context);
  745. }
  746. return context.buffer;
  747. }
  748. /**
  749. * Extracts buffered data into the provided byte[] array, starting at position bPos, up to a maximum of bAvail
  750. * bytes. Returns how many bytes were actually extracted.
  751. * <p>
  752. * Package protected for access from I/O streams.
  753. *
  754. * @param b
  755. * byte[] array to extract the buffered data into.
  756. * @param bPos
  757. * position in byte[] array to start extraction at.
  758. * @param bAvail
  759. * amount of bytes we're allowed to extract. We may extract fewer (if fewer are available).
  760. * @param context
  761. * the context to be used
  762. * @return The number of bytes successfully extracted into the provided byte[] array.
  763. */
  764. int readResults(final byte[] b, final int bPos, final int bAvail, final Context context) {
  765. if (context.buffer != null) {
  766. final int len = Math.min(available(context), bAvail);
  767. System.arraycopy(context.buffer, context.readPos, b, bPos, len);
  768. context.readPos += len;
  769. if (context.readPos >= context.pos) {
  770. context.buffer = null; // so hasData() will return false, and this method can return -1
  771. }
  772. return len;
  773. }
  774. return context.eof ? EOF : 0;
  775. }
  776. /**
  777. * Checks if a byte value is whitespace or not.
  778. * Whitespace is taken to mean: space, tab, CR, LF
  779. * @param byteToCheck
  780. * the byte to check
  781. * @return true if byte is whitespace, false otherwise
  782. */
  783. protected static boolean isWhiteSpace(final byte byteToCheck) {
  784. switch (byteToCheck) {
  785. case ' ' :
  786. case '\n' :
  787. case '\r' :
  788. case '\t' :
  789. return true;
  790. default :
  791. return false;
  792. }
  793. }
  794. /**
  795. * Encodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of
  796. * the Encoder interface, and will throw an EncoderException if the supplied object is not of type byte[].
  797. *
  798. * @param obj
  799. * Object to encode
  800. * @return An object (of type byte[]) containing the Base-N encoded data which corresponds to the byte[] supplied.
  801. * if the parameter supplied is not of type byte[]
  802. */
  803. public Object encode(final Object obj) throws Exception {
  804. if (!(obj instanceof byte[])) {
  805. throw new Exception("Parameter supplied to Base-N encode is not a byte[]");
  806. }
  807. return encode((byte[]) obj);
  808. }
  809. /**
  810. * Encodes a byte[] containing binary data, into a String containing characters in the Base-N alphabet.
  811. * Uses UTF8 encoding.
  812. *
  813. * @param pArray
  814. * a byte array containing binary data
  815. * @return A String containing only Base-N character data
  816. * @throws UnsupportedEncodingException
  817. */
  818. public String encodeToString(final byte[] pArray) throws UnsupportedEncodingException {
  819. return new String(encode(pArray), "UTF-8");
  820. }
  821. /**
  822. * Encodes a byte[] containing binary data, into a String containing characters in the appropriate alphabet.
  823. * Uses UTF8 encoding.
  824. *
  825. * @param pArray a byte array containing binary data
  826. * @return String containing only character data in the appropriate alphabet.
  827. * @throws UnsupportedEncodingException
  828. */
  829. public String encodeAsString(final byte[] pArray) throws UnsupportedEncodingException{
  830. return new String(encode(pArray), "UTF-8");
  831. }
  832. /**
  833. * Decodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of
  834. * the Decoder interface, and will throw a DecoderException if the supplied object is not of type byte[] or String.
  835. *
  836. * @param obj
  837. * Object to decode
  838. * @return An object (of type byte[]) containing the binary data which corresponds to the byte[] or String
  839. * supplied.
  840. * if the parameter supplied is not of type byte[]
  841. */
  842. public Object decode(final Object obj) throws Exception {
  843. if (obj instanceof byte[]) {
  844. return decode((byte[]) obj);
  845. } else if (obj instanceof String) {
  846. return decode((String) obj);
  847. } else {
  848. throw new Exception("Parameter supplied to Base-N decode is not a byte[] or a String");
  849. }
  850. }
  851. /**
  852. * Decodes a String containing characters in the Base-N alphabet.
  853. *
  854. * @param pArray
  855. * A String containing Base-N character data
  856. * @return a byte array containing binary data
  857. * @throws UnsupportedEncodingException
  858. */
  859. public byte[] decode(final String pArray) throws UnsupportedEncodingException {
  860. return decode(pArray.getBytes("UTF-8"));
  861. }
  862. /**
  863. * Decodes a byte[] containing characters in the Base-N alphabet.
  864. *
  865. * @param pArray
  866. * A byte array containing Base-N character data
  867. * @return a byte array containing binary data
  868. */
  869. public byte[] decode(final byte[] pArray) {
  870. if (pArray == null || pArray.length == 0) {
  871. return pArray;
  872. }
  873. final Context context = new Context();
  874. decode(pArray, 0, pArray.length, context);
  875. decode(pArray, 0, EOF, context); // Notify decoder of EOF.
  876. final byte[] result = new byte[context.pos];
  877. readResults(result, 0, result.length, context);
  878. return result;
  879. }
  880. /**
  881. * Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.
  882. *
  883. * @param pArray
  884. * a byte array containing binary data
  885. * @return A byte array containing only the basen alphabetic character data
  886. */
  887. public byte[] encode(final byte[] pArray) {
  888. if (pArray == null || pArray.length == 0) {
  889. return pArray;
  890. }
  891. final Context context = new Context();
  892. encode(pArray, 0, pArray.length, context);
  893. encode(pArray, 0, EOF, context); // Notify encoder of EOF.
  894. final byte[] buf = new byte[context.pos - context.readPos];
  895. readResults(buf, 0, buf.length, context);
  896. return buf;
  897. }
  898. // package protected for access from I/O streams
  899. abstract void encode(byte[] pArray, int i, int length, Context context);
  900. // package protected for access from I/O streams
  901. abstract void decode(byte[] pArray, int i, int length, Context context);
  902. /**
  903. * Returns whether or not the <code>octet</code> is in the current alphabet.
  904. * Does not allow whitespace or pad.
  905. *
  906. * @param value The value to test
  907. *
  908. * @return {@code true} if the value is defined in the current alphabet, {@code false} otherwise.
  909. */
  910. protected abstract boolean isInAlphabet(byte value);
  911. /**
  912. * Tests a given byte array to see if it contains only valid characters within the alphabet.
  913. * The method optionally treats whitespace and pad as valid.
  914. *
  915. * @param arrayOctet byte array to test
  916. * @param allowWSPad if {@code true}, then whitespace and PAD are also allowed
  917. *
  918. * @return {@code true} if all bytes are valid characters in the alphabet or if the byte array is empty;
  919. * {@code false}, otherwise
  920. */
  921. public boolean isInAlphabet(final byte[] arrayOctet, final boolean allowWSPad) {
  922. for (int i = 0; i < arrayOctet.length; i++) {
  923. if (!isInAlphabet(arrayOctet[i]) &&
  924. (!allowWSPad || (arrayOctet[i] != PAD) && !isWhiteSpace(arrayOctet[i]))) {
  925. return false;
  926. }
  927. }
  928. return true;
  929. }
  930. /**
  931. * Tests a given String to see if it contains only valid characters within the alphabet.
  932. * The method treats whitespace and PAD as valid.
  933. *
  934. * @param basen String to test
  935. * @return {@code true} if all characters in the String are valid characters in the alphabet or if
  936. * the String is empty; {@code false}, otherwise
  937. * @throws UnsupportedEncodingException
  938. * @see #isInAlphabet(byte[], boolean)
  939. */
  940. public boolean isInAlphabet(final String basen) throws UnsupportedEncodingException {
  941. return isInAlphabet(basen.getBytes("UTF-8"), true);
  942. }
  943. /**
  944. * Tests a given byte array to see if it contains any characters within the alphabet or PAD.
  945. *
  946. * Intended for use in checking line-ending arrays
  947. *
  948. * @param arrayOctet
  949. * byte array to test
  950. * @return {@code true} if any byte is a valid character in the alphabet or PAD; {@code false} otherwise
  951. */
  952. protected boolean containsAlphabetOrPad(final byte[] arrayOctet) {
  953. if (arrayOctet == null) {
  954. return false;
  955. }
  956. for (final byte element : arrayOctet) {
  957. if (PAD == element || isInAlphabet(element)) {
  958. return true;
  959. }
  960. }
  961. return false;
  962. }
  963. /**
  964. * Calculates the amount of space needed to encode the supplied array.
  965. *
  966. * @param pArray byte[] array which will later be encoded
  967. *
  968. * @return amount of space needed to encoded the supplied array.
  969. * Returns a long since a max-len array will require > Integer.MAX_VALUE
  970. */
  971. public long getEncodedLength(final byte[] pArray) {
  972. // Calculate non-chunked size - rounded up to allow for padding
  973. // cast to long is needed to avoid possibility of overflow
  974. long len = ((pArray.length + unencodedBlockSize-1) / unencodedBlockSize) * (long) encodedBlockSize;
  975. if (lineLength > 0) { // We're using chunking
  976. // Round up to nearest multiple
  977. len += ((len + lineLength-1) / lineLength) * chunkSeparatorLength;
  978. }
  979. return len;
  980. }
  981. }