package cn.hnthyy.thmz.Utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

import sun.misc.BASE64Encoder;

/**
 * MD5加密工具类
 */
public class Md5Util {
    private static int inc = 0;
    /**
     * 利用MD5进行加密
     */
    public static String encoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //确定计算方法
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder base64en = new BASE64Encoder();
        //加密后的字符串
        String newStr = base64en.encode(md5.digest(str.getBytes("utf-8")));
        return newStr;
    }

    /**
     * 判断用户密码是否正确
     * newPassword 用户输入的明文密码
     * oldPassword 数据库存储的加密密码
     */
    public static boolean checkPassword(String newPassword, String oldPassword) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        if (encoderByMd5(newPassword).equals(oldPassword))
            return true;
        else
            return false;
    }


    /**
     * 获取流水号
     * @return
     */
    public static String getReceiptNo(){
        long id = Long.parseLong(String.valueOf(System.currentTimeMillis())
                .substring(1,10)
                .concat(String.valueOf(inc)));
        inc = (inc+1)%10;
        SimpleDateFormat smf = new SimpleDateFormat("yyMMdd");
        return smf.format(new Date())+id;
    }
}