generate Id via hash from object array - Android java.security

Android examples for java.security:Hash

Description

generate Id via hash from object array

Demo Code


//package com.java2s;
import java.security.MessageDigest;

public class Main {
    private static final Object sLock = new Object();
    private static MessageDigest md;

    public static long generateId(Object... value) {
        if (md == null) {
            return 0L;
        }//from w w  w  . jav  a2 s. co m
        //String value to be converted
        StringBuilder builder = new StringBuilder();
        for (Object s : value) {
            builder.append(String.valueOf(s));
        }
        byte[] hashValBytes;
        synchronized (sLock) {
            md.reset();
            //convert the string value to a byte array and pass it into the hash algorithm
            md.update(builder.toString().getBytes());

            //retrieve a byte array containing the digest
            hashValBytes = md.digest();
        }

        long hashValLong = 0;

        //create a long value from the byte array
        for (int i = 0; i < 8; i++) {
            hashValLong |= ((long) (hashValBytes[i]) & 0x0FF) << (8 * i);
        }
        return hashValLong;
    }
}

Related Tutorials