package sdf;

import com.sunyard.chsm.enums.ManufacturerModelEnum;
import com.sunyard.chsm.sdf.adapter.SdfApiAdapter;
import com.sunyard.chsm.sdf.adapter.SdfApiAdapterFactory;
import com.sunyard.chsm.sdf.context.AlgId;
import com.sunyard.chsm.sdf.model.DeviceInfo;
import com.sunyard.chsm.sdf.model.EccCipher;
import com.sunyard.chsm.sdf.model.EccKey;
import com.sunyard.chsm.sdf.model.EccPriKey;
import com.sunyard.chsm.sdf.model.EccPubKey;
import com.sunyard.chsm.sdf.model.EccSignature;
import com.sunyard.chsm.utils.CodecUtils;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import java.util.Optional;

/**
 * @author liulu
 * @since 2024/12/12
 */
@Slf4j
class SdfApiAdapterTest {

    private final static byte[] symKey = "nhkdhaksd4678787".getBytes();
    private final static byte[] iv = "hjdashde83252i23".getBytes();
    private final static String plain = "hello sdf api ,hello sdf api !&!";
    private final static String ip1 = "172.16.18.41";
    private final static int port = 8889;
    private static final SdfApiAdapter bcAdapter = SdfApiAdapterFactory.getBcAdapter();
    private static final SdfApiAdapter sdfAdapter = SdfApiAdapterFactory.newInstance(ManufacturerModelEnum.enc001.getModel(), ip1, port);

    private static String hd;
    private static String hs;
    private static EccPubKey pubKey;
    private static EccPriKey priKey;


    @BeforeAll
    public static void before() throws Exception {
        hd = sdfAdapter.openDevice();
        hs = sdfAdapter.openSession(hd);
        EccKey eccKey = sdfAdapter.generateKeyPairECC(hs, AlgId.SGD_SM2_3);
        pubKey = com.sunyard.chsm.sdf.model.EccPubKey.fromBytes(eccKey.getPubKey());
        priKey = com.sunyard.chsm.sdf.model.EccPriKey.fromBytes(eccKey.getPriKey());
        log.info("public key: {}", pubKey.getPubKeyHex());
        log.info("private key: {}", CodecUtils.encodeHex(priKey.getD()));
    }

    @AfterAll
    public static void after() {
        Optional.ofNullable(hs).ifPresent(sdfAdapter::closeSession);
        Optional.ofNullable(hd).ifPresent(sdfAdapter::closeDevice);
    }

    @Test
    public void getDeviceInfo() {
        DeviceInfo deviceInfo = sdfAdapter.getDeviceInfo(hs);
        Assertions.assertNotNull(deviceInfo);
        log.info("DeviceInfo: {}", deviceInfo);
    }

    @Test
    public void testSymEncAndDec() {
        String hk = sdfAdapter.importKey(hs, symKey);
        byte[] ecbCipher = sdfAdapter.symEncrypt(hs, hk, AlgId.SGD_SM4_ECB, null, plain.getBytes());
        byte[] ecbPlain = sdfAdapter.symDecrypt(hs, hk, AlgId.SGD_SM4_ECB, null, ecbCipher);
        log.info("ecb_cipher: {}", CodecUtils.encodeHex(ecbCipher));
        Assertions.assertEquals(plain, new String(ecbPlain));

        byte[] cbcCipher = sdfAdapter.symEncrypt(hs, hk, AlgId.SGD_SM4_CBC, iv, plain.getBytes());
        log.info("cbc_cipher: {}", CodecUtils.encodeHex(cbcCipher));
        byte[] cbcPlain = sdfAdapter.symDecrypt(hs, hk, AlgId.SGD_SM4_CBC, iv, cbcCipher);
        Assertions.assertEquals(plain, new String(cbcPlain));
        sdfAdapter.destroyKey(hs, hk);

        Assertions.assertArrayEquals(ecbPlain, cbcPlain);
        Assertions.assertNotEquals(CodecUtils.encodeHex(ecbCipher), CodecUtils.encodeHex(cbcCipher));


        String bchk = bcAdapter.importKey("", symKey);
        byte[] bcEcbCipher = bcAdapter.symEncrypt("", bchk, AlgId.SGD_SM4_ECB, null, plain.getBytes());
        log.info("bc_ecb_cipher: {}", CodecUtils.encodeHex(bcEcbCipher));
        Assertions.assertArrayEquals(ecbCipher, bcEcbCipher);

        byte[] bcCbcCipher = bcAdapter.symEncrypt("", bchk, AlgId.SGD_SM4_CBC, iv, plain.getBytes());
        log.info("bc_cbc_cipher: {}", CodecUtils.encodeHex(bcCbcCipher));
        bcAdapter.destroyKey(hs, bchk);
        Assertions.assertArrayEquals(cbcCipher, bcCbcCipher);
    }

    @Test
    public void testSM2EncAndDec() {
        EccCipher sdfCipher = sdfAdapter.externalEncryptECC(hs, pubKey, plain.getBytes());
        log.info("sdf sm2 cipher: {}", sdfCipher.getC1C3C2Hex());
        byte[] bcPlain = bcAdapter.externalDecryptECC("", priKey, sdfCipher);
        log.info("bc sm2 plain: {}", new String(bcPlain));
        Assertions.assertEquals(plain, new String(bcPlain));

        EccCipher bcCipher = bcAdapter.externalEncryptECC("", pubKey, plain.getBytes());
        log.info("bc sm2 cipher: {}", bcCipher.getC1C3C2Hex());
        byte[] sm2Plain = sdfAdapter.externalDecryptECC(hs, priKey, bcCipher);
        log.info("sdf sm2 plain: {}", new String(sm2Plain));

        Assertions.assertEquals(plain, new String(sm2Plain));
    }

    @Test
    public void testSM2SignAndVerify() {
        EccSignature bcSign = bcAdapter.externalSignECC("", priKey, plain.getBytes());
        log.info("bc sm2 signature: {}", bcSign.getRawSignHex());
        boolean sdfVerified = sdfAdapter.externalVerifyECC(hs, pubKey, plain.getBytes(), bcSign);
        log.info("sdf sm2 verified: {}", sdfVerified);
        Assertions.assertTrue(sdfVerified);

        EccSignature sdfSign = sdfAdapter.externalSignECC(hs, priKey, plain.getBytes());
        log.info("sdf sm2 signature: {}", sdfSign.getRawSignHex());
        boolean bcVerified = bcAdapter.externalVerifyECC("", pubKey, plain.getBytes(), sdfSign);
        log.info("bc sm2 verified: {}", bcVerified);
        Assertions.assertTrue(bcVerified);
    }

    @Test
    public void testHash() {
        String newSession = sdfAdapter.openSession(hd);
        sdfAdapter.hashInit(newSession, AlgId.SGD_SM3, null, new byte[0]);
        sdfAdapter.hashUpdate(newSession, plain.getBytes());
        byte[] hash = sdfAdapter.hashFinish(newSession);
        log.info("sdf hash: {}", CodecUtils.encodeHex(hash));
        sdfAdapter.closeSession(newSession);

        String bcNewSession = bcAdapter.openSession("");
        bcAdapter.hashInit(bcNewSession, AlgId.SGD_SM3, null, new byte[0]);
        bcAdapter.hashUpdate(bcNewSession, plain.getBytes());
        byte[] bcHash = bcAdapter.hashFinish(bcNewSession);
        log.info("bc hash: {}", CodecUtils.encodeHex(bcHash));
        bcAdapter.closeSession(bcNewSession);

        Assertions.assertArrayEquals(hash, bcHash);
    }

    @Test
    public void testSm4Mac() {
        String hk = sdfAdapter.importKey(hs, symKey);
        byte[] sdfMac = sdfAdapter.calculateMAC(hs, hk, AlgId.SGD_SM4_MAC, iv, plain.getBytes());
        log.info("sdf mac: {}", CodecUtils.encodeHex(sdfMac));
        sdfAdapter.destroyKey(hs, hk);

        String bchk = bcAdapter.importKey("", symKey);
        byte[] bcMac = bcAdapter.calculateMAC("", bchk, AlgId.SGD_SM4_MAC, iv, plain.getBytes());
        log.info("bc mac: {}", CodecUtils.encodeHex(bcMac));
        bcAdapter.destroyKey("", bchk);
        Assertions.assertArrayEquals(sdfMac, bcMac);
    }

    @Test
    public void testRandom() {
        byte[] r = sdfAdapter.generateRandom(hs, 64);
        Assertions.assertEquals(64, r.length);
    }


}
