package info.aspirecn.iov.sjjh.supplier10000027.util;

import cn.com.jit.new_vstk.exception.NewCSSException;
import cn.org.bjca.client.exceptions.ApplicationNotFoundException;
import cn.org.bjca.client.exceptions.InitException;
import cn.org.bjca.client.exceptions.SVSConnectException;
import cn.org.bjca.client.security.SecurityEngineDeal;
import com.fri.ctid.security.jit.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;

/**
 * Created by on 2018/3/21.
 * 签名数据
 */
@Slf4j
@Component
public class DataSignature {
    private static String BJCAROOT_URL;

    @Value("${custom.bjcaRoot}")
    private String bjcaRoot;

    private static String certID = "ywzd";//改成自己的ywzd站点号

    static BASE64Encoder be = new BASE64Encoder();
    static BASE64Decoder bd = new BASE64Decoder();

    static Api api = new Api();
    static com.fri.ctid.security.bjca.Api api2 = new com.fri.ctid.security.bjca.Api();

    //签名方法(吉大正元)
    public static String signature(byte[] data) throws NewCSSException, IOException {
        System.out.println(Arrays.toString(data));
        api.initConnection("./config/cssconfig.properties");
        byte[] signReturn = api.p7Sign(data,certID);
        System.out.println("签名"+Arrays.toString(signReturn));
        String sr = new String(be.encodeBuffer(signReturn));
        System.out.println("BASE64后"+sr);
        return sr;
    }

//    //签名(北京CA)
    public static String signDataByP7DetachForJit(String inData) throws IOException, NewCSSException {
        File directory = new File("/usr/share/bjcaRoot");//参数为空
        String courseFile = directory.getCanonicalPath();//标准的路径 ;
        log.info("bjcaRoot == " + courseFile);
        api2.initConnection(courseFile);
//        api2.initConnection("C:/BJCAROOT");
        byte[]  signedValue  = com.fri.ctid.security.bjca.Api.p7Sign(inData.getBytes(),"SVSQm");
        String sv = new String(signedValue);
        return sv;
    }


    //验签方法(吉大正元)
    public static boolean encryptEnvelope(byte[] data ,byte [] sign) throws NewCSSException {
        api.initConnection("./config/cssconfig.properties");
        boolean result = api.p7SignVerify(data,sign);
        return result;
    }

//    //验签方法(北京CA)
    public static boolean encryptEnvelopeCa(byte[] data ,byte [] sign) throws NewCSSException {
        boolean verifySignRes = com.fri.ctid.security.bjca.Api.p7SignVerify(data,sign);
        return verifySignRes;
    }

    @PostConstruct
    public void setBjcarootUrl() {
        BJCAROOT_URL = this.bjcaRoot;
    }
}
