Guest User

Untitled

a guest
Dec 12th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.70 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class Base64 {
  4.  
  5. public static void main(String[] args) {
  6. byte[] bytes = "ABCDEFG".getBytes();
  7. String encoded = encode(bytes);
  8. if (encoded.equals("QUJDREVGRw==") == false) {
  9. throw new AssertionError(encoded);
  10. }
  11.  
  12. byte[] decoded = decode(encoded);
  13. if (Arrays.equals(decoded, bytes) == false) {
  14. throw new AssertionError(new String(decoded));
  15. }
  16. }
  17.  
  18. private static final char[] CONVERSION_TABLE =
  19. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
  20. .toCharArray();
  21.  
  22. public static String encode(byte[] bs) {
  23. int l = bs.length;
  24. int q = l / 3;
  25. int m = l % 3;
  26. char[] cs = new char[(q + (m == 0 ? 0 : 1)) * 4];
  27. int index = 0;
  28. for (int i = 0; i < q; i++) {
  29. int a = bs[i * 3] << 16 | bs[i * 3 + 1] << 8 | bs[i * 3 + 2];
  30. cs[index++] = CONVERSION_TABLE[a >> 18 & 0x3f];
  31. cs[index++] = CONVERSION_TABLE[a >> 12 & 0x3f];
  32. cs[index++] = CONVERSION_TABLE[a >> 6 & 0x3f];
  33. cs[index++] = CONVERSION_TABLE[a & 0x3f];
  34. }
  35. if (m == 2) {
  36. int a = bs[l - 2] << 8 | bs[l - 1];
  37. cs[index++] = CONVERSION_TABLE[a >> 10 & 0x3f];
  38. cs[index++] = CONVERSION_TABLE[a >> 4 & 0x3f];
  39. cs[index++] = CONVERSION_TABLE[a << 2 & 0x3f];
  40. } else if (m == 1) {
  41. int a = bs[l - 1];
  42. cs[index++] = CONVERSION_TABLE[a >> 2 & 0x3f];
  43. cs[index++] = CONVERSION_TABLE[a << 4 & 0x3f];
  44. }
  45. while (index < cs.length) {
  46. cs[index++] = '=';
  47. }
  48. return String.valueOf(cs);
  49. }
  50.  
  51. public static byte[] decode(String text) {
  52. char[] cs = text.toCharArray();
  53. int q = cs.length / 4;
  54. byte[] bs = new byte[q * 3];
  55. int index = 0;
  56. for (int i = 0; i < q; i++) {
  57. int a =
  58. indexOf(cs[i * 4]) << 18
  59. | indexOf(cs[i * 4 + 1]) << 12
  60. | indexOf(cs[i * 4 + 2]) << 6
  61. | indexOf(cs[i * 4 + 3]);
  62. bs[index++] = (byte) (a >> 16);
  63. bs[index++] = (byte) (a >> 8);
  64. bs[index++] = (byte) a;
  65. }
  66. while (bs[--index] == 0) {
  67. }
  68. return Arrays.copyOf(bs, index + 1);
  69. }
  70.  
  71. private static int indexOf(char c) {
  72. if (c == '+') {
  73. return 62;
  74. } else if (c == '/') {
  75. return 63;
  76. } else if ('A' <= c && c <= 'Z') {
  77. return c - 65;
  78. } else if ('a' <= c && c <= 'z') {
  79. return c - 71;
  80. } else if ('0' <= c && c <= '9') {
  81. return c + 4;
  82. }
  83. return 0;
  84. }
  85. }
Add Comment
Please, Sign In to add comment