Hash String to Sha1 - Android java.security

Android examples for java.security:Hash

Description

Hash String to Sha1

Demo Code


//package com.java2s;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static String toSha1(String text)
            throws UnsupportedEncodingException, NoSuchAlgorithmException,
            InvalidKeyException {

        MessageDigest digest = MessageDigest.getInstance("SHA-1");

        digest.reset();//from  w ww.  j a  va 2s . co  m

        byte[] data = digest.digest(text.getBytes("UTF8"));

        StringBuilder hash = new StringBuilder();

        for (byte item : data) {

            String h = Integer.toHexString(0xFF & item);

            while (h.length() < 2) {
                h = "0" + h;
            }

            hash.append(h);
        }

        return hash.toString();
    }
}

Related Tutorials