1 package com.thoughtworks.xstream.core.util; 2 3 import java.io.ByteArrayOutputStream ; 4 import java.io.IOException ; 5 import java.io.Reader ; 6 import java.io.StringReader ; 7 8 19 public class Base64Encoder { 20 21 40 private static final char[] SIXTY_FOUR_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); 41 private static final int[] REVERSE_MAPPING = new int[123]; 42 43 static { 44 for (int i = 0; i < SIXTY_FOUR_CHARS.length; i++) REVERSE_MAPPING[SIXTY_FOUR_CHARS[i]] = i + 1; 45 } 46 47 public String encode(byte[] input) { 48 StringBuffer result = new StringBuffer (); 49 int outputCharCount = 0; 50 for (int i = 0; i < input.length; i += 3) { 51 int remaining = Math.min(3, input.length - i); 52 int oneBigNumber = (input[i] & 0xff) << 16 | (remaining <= 1 ? 0 : input[i + 1] & 0xff) << 8 | (remaining <= 2 ? 0 : input[i + 2] & 0xff); 53 for (int j = 0; j < 4; j++) result.append(remaining + 1 > j ? SIXTY_FOUR_CHARS[0x3f & oneBigNumber >> 6 * (3 - j)] : '='); 54 if ((outputCharCount += 4) % 76 == 0) result.append('\n'); 55 } 56 return result.toString(); 57 } 58 59 public byte[] decode(String input) { 60 try { 61 ByteArrayOutputStream out = new ByteArrayOutputStream (); 62 StringReader in = new StringReader (input); 63 for (int i = 0; i < input.length(); i += 4) { 64 int a[] = {mapCharToInt(in), mapCharToInt(in), mapCharToInt(in), mapCharToInt(in)}; 65 int oneBigNumber = (a[0] & 0x3f) << 18 | (a[1] & 0x3f) << 12 | (a[2] & 0x3f) << 6 | (a[3] & 0x3f); 66 for (int j = 0; j < 3; j++) if (a[j + 1] >= 0) out.write(0xff & oneBigNumber >> 8 * (2 - j)); 67 } 68 return out.toByteArray(); 69 } catch (IOException e) { 70 throw new Error (e + ": " + e.getMessage()); 71 } 72 } 73 74 private int mapCharToInt(Reader input) throws IOException { 75 int c; 76 while ((c = input.read()) != -1) { 77 int result = REVERSE_MAPPING[c]; 78 if (result != 0) return result -1; 79 if (c == '=') return -1; 80 } 81 return -1; 82 } 83 } 84 | Popular Tags |