get String Kemata Hash - Java java.lang

Java examples for java.lang:String Hash

Description

get String Kemata Hash

Demo Code

/*/*  w  w w  .j a v a  2 s .  co m*/
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static void main(String[] argv) throws Exception {
        String key = "java2s.com";
        System.out.println(getKemataHash(key));
    }

    public static long getKemataHash(String key) {

        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 not supported", e);
        }

        byte[] rtv = null;
        synchronized (md5) { // md5 implement is un-thread-safty
            md5.reset();
            byte[] codes = null;
            try {
                codes = key.getBytes("UTF-8");
            } catch (UnsupportedEncodingException ex) {
                new RuntimeException(ex);
            }
            md5.update(codes);
            rtv = md5.digest();
        }
        return ((long) rtv[rtv.length - 1] << 56)
                + ((long) (rtv[rtv.length - 2] & 255) << 48)
                + ((long) (rtv[rtv.length - 3] & 255) << 40)
                + ((long) (rtv[rtv.length - 4] & 255) << 32)
                + ((long) (rtv[rtv.length - 5] & 255) << 24)
                + ((rtv[rtv.length - 6] & 255) << 16)
                + ((rtv[rtv.length - 7] & 255) << 8)
                + ((rtv[rtv.length - 8] & 255) << 0);
    }
}

Related Tutorials