1 18 package org.apache.tools.ant.util; 19 20 26 public class Base64Converter { 27 28 private static final char[] ALPHABET = { 29 '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', '+', '/'}; 38 40 public static final char[] alphabet = ALPHABET; 41 43 44 49 public String encode(String s) { 50 return encode(s.getBytes()); 51 } 52 53 58 public String encode(byte[] octetString) { 59 int bits24; 60 int bits6; 61 62 char[] out = new char[((octetString.length - 1) / 3 + 1) * 4]; 63 int outIndex = 0; 64 int i = 0; 65 66 while ((i + 3) <= octetString.length) { 67 bits24 = (octetString[i++] & 0xFF) << 16; 69 bits24 |= (octetString[i++] & 0xFF) << 8; 70 bits24 |= octetString[i++]; 71 72 bits6 = (bits24 & 0x00FC0000) >> 18; 73 out[outIndex++] = ALPHABET[bits6]; 74 bits6 = (bits24 & 0x0003F000) >> 12; 75 out[outIndex++] = ALPHABET[bits6]; 76 bits6 = (bits24 & 0x00000FC0) >> 6; 77 out[outIndex++] = ALPHABET[bits6]; 78 bits6 = (bits24 & 0x0000003F); 79 out[outIndex++] = ALPHABET[bits6]; 80 } 81 if (octetString.length - i == 2) { 82 bits24 = (octetString[i] & 0xFF) << 16; 84 bits24 |= (octetString[i + 1] & 0xFF) << 8; 85 bits6 = (bits24 & 0x00FC0000) >> 18; 86 out[outIndex++] = ALPHABET[bits6]; 87 bits6 = (bits24 & 0x0003F000) >> 12; 88 out[outIndex++] = ALPHABET[bits6]; 89 bits6 = (bits24 & 0x00000FC0) >> 6; 90 out[outIndex++] = ALPHABET[bits6]; 91 92 out[outIndex++] = '='; 94 } else if (octetString.length - i == 1) { 95 bits24 = (octetString[i] & 0xFF) << 16; 97 bits6 = (bits24 & 0x00FC0000) >> 18; 98 out[outIndex++] = ALPHABET[bits6]; 99 bits6 = (bits24 & 0x0003F000) >> 12; 100 out[outIndex++] = ALPHABET[bits6]; 101 102 out[outIndex++] = '='; 104 out[outIndex++] = '='; 105 } 106 return new String (out); 107 } 108 } 109 | Popular Tags |