get String UTF8 SHA1 Hash - Android java.security

Android examples for java.security:Hash

Description

get String UTF8 SHA1 Hash

Demo Code


//package com.java2s;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static String getStringUTF8SHA1(String input) {
        try {// w  w w  . java  2 s . c  om
            return getBytesHash("SHA1", input.getBytes("utf8"));
        } catch (UnsupportedEncodingException e) {
            return getBytesHash("SHA1", input.getBytes());
        }
    }

    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