44.Android MD5Util

44.Android MD5Util

public class MD5Util {

    public static String getMD5String(String key) {
        char hexDigits[] = {'0', '1', '2', '3', '4',
                '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] input = key.getBytes();
            // MD5算法的 MessageDigest 對象
            MessageDigest md5Digest = MessageDigest.getInstance("MD5");
            // 轉換
            md5Digest.update(input);
            // 密文
            byte[] md5byte = md5Digest.digest();
            // string 轉 十六進制
            int j = md5byte.length;
            char md5char[] = new char[j * 2];
            int k = 0;
            for (byte b : md5byte) {
                md5char[k++] = hexDigits[b >>> 4 & 0xf];
                md5char[k++] = hexDigits[b & 0xf];
            }
            return new String(md5char);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte aByte : bytes) {
            String hex = Integer.toHexString(255 & aByte);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章