1 16 package org.apache.jetspeed.util; 17 18 import javax.mail.internet.MimeUtility ; 19 import java.io.ByteArrayInputStream ; 20 import java.io.ByteArrayOutputStream ; 21 import java.io.InputStream ; 22 23 35 36 public class Base64 { 37 38 public static String decodeAsString(String b64string) throws Exception 39 { 40 return new String (decodeAsByteArray(b64string)); 41 } 42 43 public static byte[] decodeAsByteArray(String b64string) throws Exception 44 { 45 InputStream in = MimeUtility.decode(new ByteArrayInputStream ( 46 b64string.getBytes()), "base64"); 47 48 ByteArrayOutputStream out = new ByteArrayOutputStream (); 49 50 while(true) 51 { 52 int b = in.read(); 53 if (b == -1) break; 54 else out.write(b); 55 } 56 57 return out.toByteArray(); 58 } 59 60 public static String encodeAsString(String plaintext) throws Exception 61 { 62 return encodeAsString(plaintext.getBytes()); 63 } 64 65 public static String encodeAsString(byte[] plaindata) throws Exception 66 { 67 ByteArrayOutputStream out = new ByteArrayOutputStream (); 68 ByteArrayOutputStream inStream = new ByteArrayOutputStream (); 69 70 inStream.write(plaindata, 0, plaindata.length); 71 72 if ((plaindata.length % 3 ) == 1) 74 { 75 inStream.write(0); 76 inStream.write(0); 77 } 78 else if((plaindata.length % 3 ) == 2) 79 { 80 inStream.write(0); 81 } 82 83 inStream.writeTo(MimeUtility.encode(out, "base64")); 84 return out.toString(); 85 } 86 87 } 88 89 | Popular Tags |