首页 > 代码库 > MD5

MD5

 1 package com.core.util; 2  3 import java.security.MessageDigest; 4  5 public class MD5 { 6      7     //十六进制下数字到字符的映射数组 8     private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", 9             "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };10 11     /** 把inputString加密 */12     public static String createPassword(String inputString) {13         return encodeByMD5(inputString);14     }15 16     /**17      * 18      * Creation  Date:2008-3-1419      * TODO    验证输入的密码是否正确20      * @param password 加密后的源密码21      * @param inputString 输入字符串22      * @return boolean true为真,false为假23      * @Author tianw24      */25     public static boolean authenticatePassword(String password,26             String inputString) {27         if (password.equals(encodeByMD5(inputString))) {28             return true;29         } else {30             return false;31         }32     }33 34     35     /** 对字符串进行MD5加密 */36     private static String encodeByMD5(String originString) {37         if (originString != null) {38             try {39                 // 创建具有指定算法名称的信息摘要40                 MessageDigest md = MessageDigest.getInstance("MD5");41                 // 使用指定的字节数组对摘要进行最后更新,然后完成摘要计算42                 byte[] results = md.digest(originString.getBytes());43                 // 将得到的字节数组变成字符串返回44                 String resultString = byteArrayToHexString(results);45                 return resultString.toUpperCase();46             } catch (Exception ex) {47                 ex.printStackTrace();48             }49         }50         return null;51     }52     53     /**54      * 55      * Creation  Date:2008-3-1456      * TODO    转换字节数组为十六进制字符串57      * @param b  字节数组58      * @return String 十六进制字符串59      * @Author tianw60      */61     private static String byteArrayToHexString(byte[] b) {62         StringBuffer resultSb = new StringBuffer();63         for (int i = 0; i < b.length; i++) {64             65             String ss = byteToHexString(b[i]);            66             resultSb.append(ss);67         }68         69         return resultSb.toString();70     }71 72     73     /** 将一个字节转化成十六进制形式的字符串 */74     private static String byteToHexString(byte b) {75         int n = b;76         if (n < 0)77             n = 256 + n;78         int d1 = n / 16;79         int d2 = n % 16;80         return hexDigits[d1] + hexDigits[d2];81     }82     83     public static void main(String[] args) {84         System.out.println(MD5.createPassword("123456"));//8994E0A54CF3B38CC08F251780375F1985     }86 }

 

MD5