1 32 33 package com.imagero.uio.io; 34 35 import java.io.ByteArrayInputStream ; 36 import java.io.ByteArrayOutputStream ; 37 import java.io.IOException ; 38 39 44 public class Base64 { 45 46 private static final char encodeTable[] = { 47 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 48 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 49 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 50 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' 51 }; 52 53 static int decodeTable [] = new int[0x100]; 54 55 static { 56 for (int i = 0; i < decodeTable.length; i++) { 57 decodeTable[i] = -1; 58 } 59 for (int j = 0; j < encodeTable.length; j++) { 60 decodeTable[encodeTable[j]] = j; 61 } 62 } 63 64 70 public static String base64Encode(byte[] b) throws IOException { 71 BitInputStream bis = new BitInputStream(new ByteArrayInputStream (b)); 72 bis.setBitsToRead(6); 73 StringBuffer sb = new StringBuffer (); 74 while (true) { 75 int c = bis.read(); 76 if (c == -1) { 78 break; 79 } 80 sb.append(encodeTable[c]); 81 } 82 while ((sb.length() % 4) != 0) { 83 sb.append('='); 85 } 86 return sb.toString(); 87 } 88 89 95 public static byte[] base64Decode(String s) throws IOException { 96 char[] chrs = s.toCharArray(); 97 ByteArrayOutputStream bout = new ByteArrayOutputStream (); 98 BitOutputStream bos = new BitOutputStream(bout); 99 bos.setBitsToWrite(6); 100 101 boolean flush = true; 102 103 for (int i = 0; i < chrs.length; i++) { 104 char c = chrs[i]; 105 if (c == '=') { 107 flush = false; 108 break; 109 } 110 bos.write(decodeTable[c]); 111 } 112 if(flush) { 113 bos.flush(); 114 } 115 return bout.toByteArray(); 116 } 117 } 118 | Popular Tags |