get Bytes Digest Encrypt - Android java.security

Android examples for java.security:Decrypt Encrypt

Description

get Bytes Digest Encrypt

Demo Code


//package com.java2s;

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

public class Main {
    public static final String MD5 = "MD5";
    public static final String SHA1 = "SHA-1";
    public static final String SHA256 = "SHA-256";
    public static final String SHA384 = "SHA-384";
    public static final String SHA512 = "SHA-512";

    public static String getBytesDigestEncrypt(byte[] bytes,
            String algorithm) {//from w w  w .j  av  a2 s. co  m
        if (algorithm.equals(MD5) || algorithm.equals(SHA1)
                || algorithm.equals(SHA256) || algorithm.equals(SHA384)
                || algorithm.equals(SHA512)) {
            MessageDigest digest = null;
            try {
                digest = MessageDigest.getInstance(algorithm);
                digest.update(bytes);
                return bytes2String(digest.digest());
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String bytes2String(byte digest[]) {
        String str = "";
        String tempStr = "";
        for (int i = 0; i < digest.length; i++) {
            tempStr = (Integer.toHexString(digest[i] & 0xff));
            if (tempStr.length() == 1) {
                str = str + "0" + tempStr;
            } else {
                str += tempStr;
            }
        }
        return str;
    }
}

Related Tutorials