001 package railo.runtime.coder; 002 003 import java.io.UnsupportedEncodingException; 004 005 import org.apache.commons.codec.binary.Base64; 006 007 import railo.runtime.exp.ExpressionException; 008 import railo.runtime.op.Caster; 009 010 /** 011 * Util class to handle Base 64 Encoded Strings 012 */ 013 public final class Base64Coder { 014 015 /** 016 * decodes a Base64 String to a Plain String 017 * @param encoded 018 * @return 019 * @throws ExpressionException 020 */ 021 public static String decodeToString(String encoded,String charset) throws CoderException, UnsupportedEncodingException { 022 byte[] dec = decode(Caster.toString(encoded,null)); 023 return new String(dec,charset); 024 } 025 026 /** 027 * encodes a String to Base64 String 028 * @param plain String to encode 029 * @return encoded String 030 * @throws CoderException 031 * @throws UnsupportedEncodingException 032 */ 033 public static String encodeFromString(String plain,String charset) throws CoderException, UnsupportedEncodingException { 034 return encode(plain.getBytes(charset)); 035 } 036 037 /** 038 * encodes a byte array to Base64 String 039 * @param barr byte array to encode 040 * @return encoded String 041 * @throws CoderException 042 */ 043 public static String encode(byte[] barr) throws CoderException { 044 barr=Base64.encodeBase64(barr); 045 StringBuilder sb=new StringBuilder(); 046 for(int i=0;i<barr.length;i++) { 047 sb.append((char)barr[i]); 048 } 049 return sb.toString(); 050 } 051 052 /** 053 * decodes a Base64 String to a Plain String 054 * @param encoded 055 * @return decoded binary data 056 * @throws CoderException 057 */ 058 public static byte[] decode(String encoded) throws CoderException { 059 try { 060 char[] chars = encoded.toCharArray(); 061 byte[] bytes=new byte[chars.length]; 062 063 for(int i=0;i<chars.length;i++) { 064 bytes[i]=(byte)chars[i]; 065 } 066 return Base64.decodeBase64(bytes); 067 } 068 catch(Throwable t) { 069 throw new CoderException("can't decode input ["+encoded+"]"); 070 } 071 } 072 }