package com.platform.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;

/**
 * @author abnerhou
 * @date 2020/5/5 10:38
 * @desciption
 */
@Slf4j
public class WXCore {

    private static final String WATERMARK = "watermark";
    private static final String APPID = "appid";
    /**
     * 解密数据
     * @return
     * @throws Exception
     */
    public static JSONObject decrypt(String appId, String encryptedData, String sessionKey, String iv){
        String result = "";
        JSONObject resultJson = null;
        log.info("解密的数据为:{}" ,encryptedData);
        log.info("解密的sessionKey为:{}" , sessionKey);
        log.info("解密的iv为:{}" , iv);
        try {
            AES aes = new AES();
            byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));
            if(null != resultByte && resultByte.length > 0){
                result = new String(WxPKCS7Encoder.decode(resultByte) , "UTF-8");
                if(StringUtils.isNotBlank(result)){
                    //注意！！！这里只能用fastjson,其他的会报错，而且还是运行时错误，没法catch
                    resultJson = JSON.parseObject(result);
                    return resultJson;
                }else{
                    log.info("解密出来的的字符串为空，将返回空的json对象");
                    resultJson = new JSONObject();
                }

            }
        } catch (Exception e) {
            log.info("解密出错:{}" ,e);
        }
        return resultJson;
    }


    public static void main(String[] args) throws Exception{
        /*String appId = "o_ThP5cOX0gi4-etbb28VH6UqtoQ";
        String encryptedData = "TbhmM9MQVGKgw2PV%2FX6QVPd4Ttx1D4uC0BZN1wsP+TKqg4EMm33gVhsWgWQQis8d9d8apXNTYEKLQB9JDNVD+4C87mnJ7K5cVnHK4GcfvGeOfinxWczCLZg3eemkQMpxp2aXoPwdfnxa2VIHmBICSNcn6M6y6pIoKuA9D%2F66Ug3Xw%2FSzyk97Kkb4zjoEQp0nlVX7XQ6q96qjgOmTe0YpPg%3D%3D";
        String sessionKey = "fai1OLLccLI8em6La4zxfg==";
        String iv = "Z5PRtPk4ZtFD4wc7UyYddA%3D%3D";
        System.out.println("解密为：=" + decrypt(appId, encryptedData, sessionKey, iv));*/
        System.out.println(System.currentTimeMillis());
    }
}
