java之MD5加密

public class MD5 {

    private MessageDigest md5;
    private boolean toUpCase;

    public MD5() {
        this(false);
    }

    public MD5(boolean toUpCase) {
        this.toUpCase = toUpCase;
        try {
            md5 = MessageDigest.getInstance("MD5");// 比较慢,约16ms
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用来将一个String加工为MD5后的String
     */
    public String getMD5String(String str) {
        if (str == null) {
            return null;
        }
        try {
            byte[] dig = null;
            synchronized (md5) {
                md5.update(str.getBytes());
                dig = md5.digest();
            }
            return ByteUtil.bytesToHex(dig, toUpCase);
        } catch (Exception ex) {
            ex.printStackTrace();
            return str;
        }
    }
 

你可能感兴趣的:(MD5加密)