1 22 23 24 package org.infozone.tools; 25 26 27 35 public final class MimeBase64Encoder 36 { 37 38 39 private StringBuffer out = new StringBuffer (); 40 41 private int buf = 0; private int buf_bytes = 0; private char line[] = new char[74]; private int line_length = 0; 46 static private final byte crlf[] = "\r\n".getBytes(); 47 48 static private final char map[] = { 49 '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', '+', '/', }; 58 59 private final void encode_token() { 60 int i = line_length; 61 line[i] = map[0x3F & (buf >> 18)]; line[i+1] = map[0x3F & (buf >> 12)]; line[i+2] = map[0x3F & (buf >> 6)]; line[i+3] = map[0x3F & buf]; line_length += 4; 66 buf = 0; 67 buf_bytes = 0; 68 } 69 70 private final void encode_partial_token() { 71 int i = line_length; 72 line[i] = map[0x3F & (buf >> 18)]; line[i+1] = map[0x3F & (buf >> 12)]; 75 if (buf_bytes == 1) 76 line[i+2] = '='; 77 else 78 line[i+2] = map[0x3F & (buf >> 6)]; 80 if (buf_bytes <= 2) 81 line[i+3] = '='; 82 else 83 line[i+3] = map[0x3F & buf]; line_length += 4; 85 buf = 0; 86 buf_bytes = 0; 87 } 88 89 private final void flush_line() 90 { 91 out.append(line, 0, line_length); 92 line_length = 0; 93 } 94 95 100 public final void translate(byte[] in) 101 { 102 int in_length = in.length; 103 104 for (int i = 0; i < in_length; i++) { 105 if (buf_bytes == 0) 106 buf = (buf & 0x00FFFF) | (in[i] << 16); 107 else if (buf_bytes == 1) 108 buf = (buf & 0xFF00FF) | ((in[i] << 8) & 0x00FFFF); 109 else 110 buf = (buf & 0xFFFF00) | (in[i] & 0x0000FF); 111 112 if ((++buf_bytes) == 3) { 113 encode_token(); 114 if (line_length >= 72) { 115 flush_line(); 116 } 117 } 118 119 if (i == (in_length-1)) { 120 if ((buf_bytes > 0) && (buf_bytes < 3)) 121 encode_partial_token(); 122 if (line_length > 0) 123 flush_line(); 124 } 125 } 126 127 for (int i=0; i<line.length; i++) 128 line[i] = 0; 129 } 130 131 132 public char[] getCharArray() 133 { 134 char[] ch; 135 136 if (buf_bytes != 0) 137 encode_partial_token(); 138 flush_line(); 139 for (int i=0; i<line.length; i++) 140 line[i] = 0; 141 ch = new char[ out.length() ]; 142 out.getChars( 0, out.length(), ch, 0 ); 143 return ch; 144 } 145 } 146 | Popular Tags |