Base64Util.java 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package com.ruoyi.common.utils;
  2. /**
  3. * Base64 工具类
  4. */
  5. public class Base64Util {
  6. private static final char last2byte = (char) Integer.parseInt("00000011", 2);
  7. private static final char last4byte = (char) Integer.parseInt("00001111", 2);
  8. private static final char last6byte = (char) Integer.parseInt("00111111", 2);
  9. private static final char lead6byte = (char) Integer.parseInt("11111100", 2);
  10. private static final char lead4byte = (char) Integer.parseInt("11110000", 2);
  11. private static final char lead2byte = (char) Integer.parseInt("11000000", 2);
  12. 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', '+', '/'};
  13. public Base64Util() {
  14. }
  15. public static String encode(byte[] from) {
  16. StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3);
  17. int num = 0;
  18. char currentByte = 0;
  19. int i;
  20. for (i = 0; i < from.length; ++i) {
  21. for (num %= 8; num < 8; num += 6) {
  22. switch (num) {
  23. case 0:
  24. currentByte = (char) (from[i] & lead6byte);
  25. currentByte = (char) (currentByte >>> 2);
  26. case 1:
  27. case 3:
  28. case 5:
  29. default:
  30. break;
  31. case 2:
  32. currentByte = (char) (from[i] & last6byte);
  33. break;
  34. case 4:
  35. currentByte = (char) (from[i] & last4byte);
  36. currentByte = (char) (currentByte << 2);
  37. if (i + 1 < from.length) {
  38. currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6);
  39. }
  40. break;
  41. case 6:
  42. currentByte = (char) (from[i] & last2byte);
  43. currentByte = (char) (currentByte << 4);
  44. if (i + 1 < from.length) {
  45. currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4);
  46. }
  47. }
  48. to.append(encodeTable[currentByte]);
  49. }
  50. }
  51. if (to.length() % 4 != 0) {
  52. for (i = 4 - to.length() % 4; i > 0; --i) {
  53. to.append("=");
  54. }
  55. }
  56. return to.toString();
  57. }
  58. }