package com.ajaxdemo.utils;

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

/**
 * Created by bonismo@hotmail.com
 * 下午8:18 on 15/8/29.
 * <p>
 * MD5 加密
 * 第三方插件 commons-codec:commons-codec:1.10
 *
 * 可以直接生成
 *
 * DigestUtils.md5Hex();
 */
public class MD5Util {

    /**
     * 参考 MessageDigest 源码
     */
    public static String md5(String plainText) {

        byte[] encryptedBytes = null;
        try {
            encryptedBytes = MessageDigest.getInstance("md5").digest(plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有 MD5 加密算法");
        }

        String md5Code = new BigInteger(1, encryptedBytes).toString(16);
        for (int i = 0; i < 32 - md5Code.length(); i++) {
            md5Code = "0" + md5Code;
        }
        return md5Code;
    }
}
