get Sha1 Hex - Android java.security

Android examples for java.security:Sha

Description

get Sha1 Hex

Demo Code


import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Locale;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;

public class Main{
    /**// w ww .  j a va 2 s. c  o m
     * UTF-8
     */
    public static final String UTF_8 = "UTF-8";
    
    public static String getSha1Hex(String str) throws Exception {
        if (StringUtils.isBlank(str)) {
            throw new Exception("illegal params.");
        }
        return bytesToHexString(getSha1(str.getBytes(UTF_8)));
    }
    
    public static String bytesToHexString(byte[] bytes) {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < bytes.length; ++i) {
            int v = bytes[i] & 0xff;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
    
    public static byte[] getSha1(byte[] bytes) throws Exception {
        if (bytes == null) {
            throw new Exception("illegal params.");
        }
        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
        sha1.update(bytes);
        return sha1.digest();
    }
}

Related Tutorials