android开发MD5加密工具类(一)

MD5加密工具类整理:

 1 package com.gzcivil.utils;
 2 
 3 import java.io.UnsupportedEncodingException;
 4 import java.security.MessageDigest;
 5 import java.security.NoSuchAlgorithmException;
 6 
 7 public class MD5Tool {
 8 
 9     public static String md5(String string) {
10         byte[] hash;
11         try {
12             hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
13         } catch (NoSuchAlgorithmException e) {
14             throw new RuntimeException("Huh, MD5 should be supported?", e);
15         } catch (UnsupportedEncodingException e) {
16             throw new RuntimeException("Huh, UTF-8 should be supported?", e);
17         }
18 
19         StringBuilder hex = new StringBuilder(hash.length * 2);
20         for (byte b : hash) {
21             if ((b & 0xFF) < 0x10)
22                 hex.append("0");
23             hex.append(Integer.toHexString(b & 0xFF));
24         }
25         return hex.toString();
26     }
27 
28     public static String encrypt(String data) {
29         if (data == null)
30             data = "";
31         byte[] btRet = null;
32         try {
33             btRet = _encrypt(data.getBytes("utf-8"));
34         } catch (UnsupportedEncodingException e) {
35             e.printStackTrace();
36         }
37         if (btRet == null)
38             return null;
39         return BinStr.byte2str(btRet).toLowerCase();
40     }
41 
42     /**
43      * 加密MD5
44      * 
45      * @param content
46      *            需要加密的内容
47      * @param password
48      *            加密密码
49      * @return
50      */
51     private static byte[] _encrypt(byte[] btData) {
52         try {
53             // 获得MD5摘要算法的 MessageDigest 对象
54             MessageDigest mdInst = MessageDigest.getInstance("MD5");
55             // 使用指定的字节更新摘要
56             mdInst.update(btData);
57             // 获得密文
58             return mdInst.digest();
59         } catch (Exception e) {
60             e.printStackTrace();
61             return null;
62         }
63     }
64     
65      
66 }

 

你可能感兴趣的:(android开发MD5加密工具类(一))