001/**
002 *
003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
004 *
005 * This library is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU Lesser General Public
007 * License as published by the Free Software Foundation; either 
008 * version 2.1 of the License, or (at your option) any later version.
009 * 
010 * This library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013 * Lesser General Public License for more details.
014 * 
015 * You should have received a copy of the GNU Lesser General Public 
016 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
017 * 
018 **/
019package lucee.commons.digest;
020
021public class HashUtil {
022        private static final long[] byteTable = createLookupTable();
023        private static final long HSTART = 0xBB40E64DA205B064L;
024        private static final long HMULT = 7664345821815920749L;
025        
026        public static long create64BitHash(CharSequence cs) {
027                long h = HSTART;
028                final long hmult = HMULT;
029                final long[] ht = byteTable;
030                final int len = cs.length();
031                for (int i = 0; i < len; i++) {
032                        char ch = cs.charAt(i);
033                        h = (h * hmult) ^ ht[ch & 0xff];
034                        h = (h * hmult) ^ ht[(ch >>> 8) & 0xff];
035                }
036                if(h<0)
037                        return 0-h;
038                return h;
039        }
040        
041        public static String create64BitHashAsString(CharSequence cs, int radix) {
042                return Long.toString(create64BitHash(cs), radix);
043        }
044        
045        private static final long[] createLookupTable() {
046                long[] _byteTable = new long[256];
047                long h = 0x544B2FBACAAF1684L;
048                for (int i = 0; i < 256; i++) {
049                        for (int j = 0; j < 31; j++) {
050                                h = (h >>> 7) ^ h;
051                                h = (h << 11) ^ h;
052                                h = (h >>> 10) ^ h;
053                        }
054                        _byteTable[i] = h;
055                }
056                return _byteTable;
057        }
058}