package com.judong.chuanyiserver.util;

import java.security.MessageDigest;
import java.security.SecureRandom;

public class EncryptUtils {

    /**
     * 盐值生成的长度,需要的长度除以二
     */
    private static final Integer saltLen=64;

    /**
     * 生成密文 MD5(MD5密码+128位盐值)
     * @param pwd MD5加密后的密码
     * @return
     */
    public static String createCipher(String pwd,String salt){
        return String.valueOf(StrToMD5(pwd+salt));
    }

    /**
     * 生成一个128位的盐值
     * @return 指定位数的盐值
     */
    public static String createSalt(){
        SecureRandom ranGen = null;
        ranGen =new SecureRandom();
        byte[] aesKey = new byte[saltLen];
        ranGen.nextBytes(aesKey);
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < aesKey.length; i++) {
            String hex = Integer.toHexString(0xff & aesKey[i]);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return String.valueOf(hexString);
    }

    /**
     * 字符串转为MD5
     * @param instr
     * @return
     */
    public static String StrToMD5(String instr) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            return "";
        }
        char[] charArray = instr.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
}
