001    /**
002     * Implements the Cold Fusion Function hash
003     */
004    package railo.runtime.functions.string;
005    
006    import java.security.MessageDigest;
007    
008    import railo.commons.lang.Md5;
009    import railo.commons.lang.StringUtil;
010    import railo.runtime.PageContext;
011    import railo.runtime.config.Config;
012    import railo.runtime.exp.PageException;
013    import railo.runtime.ext.function.Function;
014    import railo.runtime.op.Caster;
015    
016    public final class Hash implements Function {
017            public static String call(PageContext pc , String str) throws PageException {
018                    return call(pc,str,null,null);
019            }
020        public synchronized static String call(PageContext pc , String string, String algorithm) throws PageException {
021                    return call(pc,string,algorithm,null);
022            }
023        public synchronized static String call(PageContext pc , String string, String algorithm, String encoding) throws PageException {
024                    return invoke(pc.getConfig(), string, algorithm, encoding);
025            }
026    
027        public synchronized static String invoke(Config config, String string, String algorithm, String encoding) throws PageException {
028                    if(StringUtil.isEmpty(algorithm))algorithm="md5";
029                    else algorithm=algorithm.trim().toLowerCase();
030                    if(StringUtil.isEmpty(encoding))encoding=config.getWebCharset();
031                    
032                    
033                    try {
034                            if("md5".equals(algorithm) || "cfmx_compat".equals(algorithm)) 
035                                    return Md5.getDigestAsString(string).toUpperCase();
036                            
037                            MessageDigest md=MessageDigest.getInstance(algorithm);
038                        md.reset();
039                        md.update(string.getBytes(encoding));
040                        return Md5.stringify(md.digest()).toUpperCase();
041                    } 
042                    catch (Exception e) {
043                            throw Caster.toPageException(e);
044                    }
045            }
046    
047    }