1 package com.smartdevicelink.util;
\r
3 public class Base64 {
\r
5 private static final String defaultString = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure";
\r
7 private static char[] map = new char[64];
\r
8 private static byte[] unmap = new byte['z' + 1];
\r
11 for (char c = 'A'; c <= 'Z'; c++) {
\r
15 for (char c = 'a'; c <= 'z'; c++) {
\r
19 for (char c = '0'; c <= '9'; c++) {
\r
34 public static void main(String[] args) {
\r
36 String toEncode = defaultString;
\r
37 if (args.length > 0) {
\r
40 System.out.println(toEncode);
\r
41 String encoded = encode(toEncode.getBytes());
\r
42 System.out.println(encoded);
\r
43 String decoded = new String(decode(encoded));
\r
44 System.out.println(decoded);
\r
47 public static String encode(byte[] toEncode) {
\r
51 int srcLen = toEncode.length;
\r
52 int destLen = (srcLen * 4 + 2) / 3;
\r
53 int padLen = ((srcLen + 2) / 3) * 4;
\r
54 char[] dest = new char[padLen];
\r
56 while (iSrc < srcLen) {
\r
57 int src1 = toEncode[iSrc++];
\r
58 int src2 = (iSrc < srcLen) ? toEncode[iSrc++] : 0;
\r
59 int src3 = (iSrc < srcLen) ? toEncode[iSrc++] : 0;
\r
60 int dest1 = (src1 >>> 2);
\r
61 int dest2 = (src1 << 4) | (src2 >> 4);
\r
63 int dest3 = (src2 << 2) | (src3 >>> 6);
\r
65 int dest4 = src3 & 0x3F;
\r
66 dest[iDest++] = map[dest1];
\r
67 dest[iDest++] = map[dest2];
\r
68 dest[iDest] = iDest < destLen ? map[dest3] : '=';
\r
70 dest[iDest] = iDest < destLen ? map[dest4] : '=';
\r
74 return new String(dest);
\r
77 public static byte[] decode(String toDecode) {
\r
80 char[] src = toDecode.toCharArray();
\r
81 int srcLen = src.length;
\r
82 int destLen = ((srcLen / 4) * 3);
\r
83 if (src[srcLen - 1] == '=') {
\r
86 if (src[srcLen - 2] == '=') {
\r
89 byte[] dest = new byte[destLen];
\r
91 while (iSrc < srcLen) {
\r
92 byte src1 = unmap[src[iSrc++]];
\r
93 byte src2 = unmap[src[iSrc++]];
\r
94 byte src3 = unmap[src[iSrc++]];
\r
95 byte src4 = unmap[src[iSrc++]];
\r
96 int dest1 = (src1 << 2) | (src2 >>> 4);
\r
97 int dest2 = (src2 << 4) | (src3 >>> 2);
\r
98 int dest3 = (src3 << 6) | src4;
\r
99 dest[iDest++] = (byte) dest1;
\r
100 if (iDest < destLen) {
\r
101 dest[iDest++] = (byte) dest2;
\r
103 if (iDest < destLen) {
\r
104 dest[iDest++] = (byte) dest3;
\r