1 17 18 package org.apache.james.util; 19 20 import javax.mail.internet.MimeUtility ; 21 import java.io.BufferedReader ; 22 import java.io.ByteArrayInputStream ; 23 import java.io.ByteArrayOutputStream ; 24 import java.io.InputStreamReader ; 25 26 27 32 33 public class Base64 { 34 35 public static BufferedReader decode(String b64string) throws Exception { 36 return new BufferedReader ( 37 new InputStreamReader ( 38 MimeUtility.decode( 39 new ByteArrayInputStream ( 40 b64string.getBytes()), "base64"))); 41 } 42 43 public static String decodeAsString(String b64string) throws Exception { 44 if (b64string == null) { 45 return b64string; 46 } 47 String returnString = decode(b64string).readLine(); 48 if (returnString == null) { 49 return returnString; 50 } 51 return returnString.trim(); 52 } 53 54 public static ByteArrayOutputStream encode(String plaintext) 55 throws Exception { 56 ByteArrayOutputStream out = new ByteArrayOutputStream (); 57 byte[] in = plaintext.getBytes(); 58 ByteArrayOutputStream inStream = new ByteArrayOutputStream (); 59 inStream.write(in, 0, in.length); 60 if ((in.length % 3 ) == 1){ 62 inStream.write(0); 63 inStream.write(0); 64 } else if((in.length % 3 ) == 2){ 65 inStream.write(0); 66 } 67 inStream.writeTo( MimeUtility.encode(out, "base64") ); 68 return out; 69 } 70 71 public static String encodeAsString(String plaintext) throws Exception { 72 return encode(plaintext).toString(); 73 } 74 75 76 } 77 | Popular Tags |