java.security 生成MD5

package com.tylor.util;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author tylor
 *           2017年8月23日
 */
public class Md5Util {
    public static String getMD5(String str) {
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值
            return new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5加密出现错误");
        }
    }
    public static void main(String[] args) {
        System.out.println(Md5Util.getMD5("this is a String"));
    }
}

 

posted @ 2017-08-24 11:28  逝者如斯,随波逐流  阅读(1926)  评论(1编辑  收藏  举报