package com.jeequan.jeepay.thirdparty.channel.yspay.utils;

import cfca.sadk.algorithm.sm2.SM2PublicKey;
import cfca.sadk.org.bouncycastle.jce.provider.BouncyCastleProvider;
import cfca.sadk.org.bouncycastle.util.encoders.Base64Kit;
import cfca.sadk.x509.certificate.X509Cert;
import lombok.Getter;
import lombok.Setter;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.security.PublicKey;
import java.security.Security;

@Getter
@Setter
public class GMCertInfo implements Serializable
{
	private static final long serialVersionUID = 1L;
	private SM2PublicKey pubKeySM2;
	private PublicKey  pubKey;
	private byte[] priKey;
	private X509Cert x509Cert;

	//读取原始公钥
	public static byte[]  ReadPublicKeyFromRaw(String publickeyFile) throws Exception
	{
		FileInputStream br = null;
		try {
			br = new FileInputStream(publickeyFile);
			byte[] b1 = new byte[2000];
			int k = br.read(b1);
			byte[] b = new byte[k];
			System.arraycopy(b1, 0, b, 0, k);
			return b;
		} catch (IOException e) {

			throw e;

		} finally {
			if(br != null){
				br.close();
			}
		}
	}

	// 从X509证书文件读取公钥,Certificate只含有公钥
	// .crt .cer文件都可以读取 .cer是IE导出的公钥证书（der格式）
	// -----BEGIN CERTIFICATE-----开始 文件头不许有其它内容
	// -----END CERTIFICATE-----
	// cer公钥证书 二进制
	public void ReadPublicKeyFromX509CertificateSM2(String cerFilePath) throws Exception
	{
		Security.addProvider(new BouncyCastleProvider());
		byte[] cer =  ReadPublicKeyFromRaw(cerFilePath);
		ReadPublicKeyFromX509CertificateSM2(cer);
	}

	public void ReadPublicKeyFromX509CertificateSM2Str(String pubKey) throws Exception
	{
		Security.addProvider(new BouncyCastleProvider());
		ReadPublicKeyFromX509CertificateSM2(Base64Kit.decode(pubKey));
	}


	public void ReadPublicKeyFromX509CertificateSM2(byte[] cer) throws Exception
	{
		Security.addProvider(new BouncyCastleProvider());
		x509Cert = new X509Cert(cer);
		//获取公钥对象
		pubKeySM2 = (SM2PublicKey) x509Cert.getPublicKey();
		pubKey = x509Cert.getPublicKey();
	}

	public SM2PublicKey getPubKeySM2() {
		return pubKeySM2;
	}

	public void setPubKeySM2(SM2PublicKey pubKeySM2) {
		this.pubKeySM2 = pubKeySM2;
	}

	public PublicKey getPubKey() {
		return pubKey;
	}

	public void setPubKey(PublicKey pubKey) {
		this.pubKey = pubKey;
	}

	public byte[] getPriKey() {
		return priKey;
	}

	public void setPriKey(byte[] priKey) {
		this.priKey = priKey;
	}

	public X509Cert getX509Cert() {
		return x509Cert;
	}

	public void setX509Cert(X509Cert x509Cert) {
		this.x509Cert = x509Cert;
	}




}
