get Bytes SHA1 hash - Android java.security

Android examples for java.security:Hash

Description

get Bytes SHA1 hash

Demo Code


//package com.java2s;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static String getBytesSHA1(byte[] input) {
        return getBytesHash("SHA1", input);
    }//from   ww  w  .  ja va  2 s .  co m

    private static String getBytesHash(String algo, byte[] input) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance(algo);
            md.reset();
            md.update(input);
            byte b[] = md.digest();

            return binaryToHexString(b);
        } catch (NoSuchAlgorithmException e) {
            return String.valueOf(input.hashCode());
        }
    }

    public static String binaryToHexString(byte[] messageDigest) {
        // Create Hex String
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < messageDigest.length; i++) {
            int by = 0xFF & messageDigest[i];
            if (by < 0x10) {
                hexString.append("0").append(Integer.toHexString(by));
            } else if (by >= 0x10) {
                hexString.append(Integer.toHexString(by));
            }
        }
        return hexString.toString();
    }
}

Related Tutorials