package com.xhly.corelib.utils;

/**
 * Created by newbiechen on 2018/1/1.
 */

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

/**
 *@Description: 将字符串转化为MD5
 */

public class MD5Utils {

    public static String strToMd5By32(String str){
        String reStr = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(str.getBytes());
            StringBuffer stringBuffer = new StringBuffer();
            for (byte b : bytes){
                int bt = b&0xff;
                if (bt < 16){
                    stringBuffer.append(0);
                }
                stringBuffer.append(Integer.toHexString(bt));
            }
            reStr = stringBuffer.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return reStr;
    }

    public static String strToMd5By16(String str){
        String reStr = strToMd5By32(str);
        if (reStr != null){
            reStr = reStr.substring(8, 24);
        }
        return reStr;
    }

    public static  String getJsMD5(String password) {
        try {
            // 得到一个信息摘要器
            MessageDigest digest = MessageDigest.getInstance("md5");
            byte[] result = digest.digest(password.getBytes());
            StringBuffer buffer = new StringBuffer();
            // 把没一个byte 做一个与运算 0xff;
            for (byte b : result) {
                // 与运算
                int number = b & 0xff;// 加盐
                String str = Integer.toHexString(number);
                if (str.length() == 1) {
                    buffer.append("0");
                }
                buffer.append(str);
            }

            // 标准的md5加密后的结果
            return buffer.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }

    //获得锁定密码
    public static String getDynamicPassword(String sn) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHH");
        String format = dateFormat.format(System.currentTimeMillis());
        String pwd = sn + format;
        MD5 md5 = new MD5();
        pwd = md5.getMD5ofStr(pwd);// md5加密
        pwd = pwd.substring(pwd.length() - 8);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            char c = pwd.charAt(i);
            if (Character.isLetter(c)) {
                int lastDigit = (int) c % 10;
                sb.append(lastDigit);
            } else {
                sb.append(c);
            }
        }

        return sb.toString();
    }

}
