package com.njcn.utils.SM;


import com.njcn.utils.PubUtils;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.util.encoders.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigInteger;
import java.util.Base64;

public class SM2 {

    // 日志记录
    private static final Logger logger = LoggerFactory.getLogger(SM2.class);

    /**
     * SM2解密密碼
     *
     * @param privateKey SM2私有秘钥
     * @param encryptedData 需要解密字符串
     */
    public static String decrypt(String privateKey, String encryptedData) {
        byte[] encryptedDataByte = Hex.decode(encryptedData);

        BigInteger privateKeyD = new BigInteger(privateKey, 16);
        ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(privateKeyD, PubUtils.GetSM2ECDomain());
        //用私钥解密
        SM2Engine sm2Engine = new SM2Engine();
        sm2Engine.init(false, privateKeyParameters);

       //processBlock得到Base64格式，记得解码
        byte[] arrayOfBytes = new byte[encryptedDataByte.length];
        try {
            arrayOfBytes = Base64.getDecoder().decode(sm2Engine.processBlock(encryptedDataByte, 0, encryptedDataByte.length));
        } catch (InvalidCipherTextException e) {
            logger.error("SM2解密byte转换出错，异常为：" + e.toString());
        }
        //得到明文
        String resultData = new String(arrayOfBytes);
        return resultData;
    }

    public static void main(String[] args) {
//        System.out.println(Hex.encode(""));
//        System.out.println(Hex.decode());
    }
}
