欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

MD5加密技术

最编程 2024-02-03 08:57:31
...

MD5加密技术 MD5是哈希算法中的一种,加密强度较为适中。哈希算法有下面几个特点: ①不可逆,即使在已知加密过程的前提下,无法从密文反推回明文。 ②输出数据的长度固定。例如:MD5加密输出数据的长度固定就是32个字符。 ③输入数据不变,输出数据不变;输入数据变,输出数据都会跟着变。

/**
 * 执行MD5加密的工具方法
 * @param soucre
 * @return
 */
public static String md5(String soucre) {    
    // 1.对字符串进行校验
    boolean checkResult = stringCheck(soucre);    
    // 2.如果字符串校验失败,则抛出一个异常
    if (!checkResult) {
        throw new RuntimeException(ACConst.MESSAGE_PWD_INVALID);
    }    
    // 3.将源字符串转换为字节数组
    byte[] inputBytes = soucre.getBytes();    
    // 4.获取MessageDigest实例
    String algorithm = "md5";    
    // 5.声明变量存储加密结果
    byte[] outputBytes = null;    
    try {    
        // 6.获取MessageDigest实例
        MessageDigest digest = MessageDigest.getInstance(algorithm);    
        // 7.执行加密
        outputBytes = digest.digest(inputBytes);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }    
    // 8.把加密结果字节数组转换为字符串
    // ①声明StringBuilder
    StringBuilder builder = new StringBuilder();    
    // ②声明字符数组
    char[] characters = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E','F' };    
    // ③遍历outputBytes
    for (int i = 0; i < outputBytes.length; i++) {    
        byte b = outputBytes[i];    
        // ③取当前字节的低四位数值
        int lowValue = b & 15;    
        // ④取当前字节的高四位数值
        int highValue = (b >> 4) & 15;    
        // ⑤使用高四位和低四位的值从characters字符数组中取出对应的字符
        char lowChar = characters[lowValue];
        char highChar = characters[highValue];    
        // ⑥拼字符串
        builder.append(highChar).append(lowChar);    
    }    
    return builder.toString();
}