encrypt MD5 - Android java.security

Android examples for java.security:MD5

Description

encrypt MD5

Demo Code


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.util.Log;

public class Main{
    private static final String TAG = Md5Utils.class.getSimpleName();
    private static final String KEY_MD5 = "MD5";
    //  w w  w.  j  a v a2 s .c  o  m
    public static String encryptMD5(byte[] data) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance(KEY_MD5);
        } catch (NoSuchAlgorithmException e) {
            Log.d(TAG, "md5 ????", e);
        }
        md5.update(data);
        byte[] returnbyteArray = md5.digest();
        return byte2hex(returnbyteArray);
    }
    
    public static String encryptMD5(String str) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance(KEY_MD5);
        } catch (NoSuchAlgorithmException e) {
            Log.d(TAG, "md5 ????", e);
        }
        md5.update(str.getBytes());
        return byte2hex(md5.digest());
    }
    
    public static String encryptMD5(String str, String salt) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance(KEY_MD5);
        } catch (NoSuchAlgorithmException e) {
            Log.d(TAG, "md5 ????", e);
        }
        md5.update((str + salt).getBytes());
        return byte2hex(md5.digest());
    }
    public static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }

        return sign.toString();
    }
}

Related Tutorials