package com.kiisoo.ic.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kiisoo.ic.system.entity.PrivilageAccountDO;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;
import java.util.HashMap;
import java.util.Map;

/**
 * 密码加密类
 * @author Arvin
 *
 */
public class PasswordEncry {

    /** 指定散列算法为md5 */
	public static String algorithmName = "MD5";
    
    /** 散列迭代次数 */
    public final static int hashIterations = 2;
    
    /** 随机数生成器 */
    private static RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

    /**
     * 生成随机盐值对密码进行加密
     * @param userDO  登录识别串（用户名）
     * @return
     */
    public PrivilageAccountDO encrypt(PrivilageAccountDO userDO) {
    	userDO.setSalt(randomNumberGenerator.nextBytes().toHex());
        String newPassword = new SimpleHash(algorithmName,userDO.getPassword(), ByteSource.Util.bytes(userDO.getCredentialsSalt()),hashIterations).toHex();
        userDO.setPassword(newPassword);
        return userDO;
    }

    public static String encode(String encrypdata, String ivdata, String sessionkey){
        byte[] encrypData = Base64.decode(encrypdata);
        byte[] ivData = Base64.decode(ivdata);
        byte[] sessionKey = Base64.decode(sessionkey);
        String str = "";
        try {
            str = decrypt(sessionKey, ivData, encrypData);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if(StringUtils.isBlank(str)){
            return "";
        }
        JSONObject json = JSON.parseObject(str);
        System.out.println(str);
        String phone = json.getString("purePhoneNumber");
        return phone;
    }

    public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        //解析解密后的字符串  
        return new String(cipher.doFinal(encData), "UTF-8");
    }
}

