package api;

import com.sunyard.chsm.param.HashReq;
import com.sunyard.chsm.param.HashResp;
import com.sunyard.chsm.utils.CodecUtils;
import com.sunyard.chsm.utils.gm.BCSM3Utils;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.Arrays;

/**
 * @author liulu
 * @since 2024/12/25
 */
@Slf4j
public class HashTest extends BaseTest {

    private static final byte[] plain = new byte[1024 * 7];

    static {
        Arrays.fill(plain, (byte) 0x04);
    }


    @Test
    public void testSingleHash() {
        HashReq hashReq = new HashReq();
        hashReq.setPlainData(CodecUtils.encodeBase64(plain));
        HashResp hashResp = execute("/hash", hashReq, HashResp.class);
        log.info("hash: {}", hashResp.getHash());

        byte[] bcHash = BCSM3Utils.hash(plain);
        log.info("bc hash: {}", CodecUtils.encodeBase64(bcHash));
        Assertions.assertEquals(CodecUtils.encodeBase64(bcHash), hashResp.getHash());
    }

    @Test
    public void testMultiHash() {

        int len = 128;
        byte[] bigdata = new byte[1024 * 7 * len];
        Arrays.fill(bigdata, (byte) 0x07);

        HashReq hashReq = new HashReq();
        HashResp hashResp = execute("/multi/package/hash/init", hashReq, HashResp.class);
        log.info("hash: {}", hashResp);


        hashReq.setHandle(hashResp.getHandle());
        for (int i = 0; i < len; i++) {
            byte[] bytes = Arrays.copyOfRange(bigdata, 1024 * 7 * i, 1024 * 7 * (i + 1));
            hashReq.setPlainData(CodecUtils.encodeBase64(bytes));
            hashResp = execute("/multi/package/hash/update", hashReq, HashResp.class);
        }

        hashResp = execute("/multi/package/hash/finish", hashReq, HashResp.class);
        log.info("hash: {}", hashResp);


        byte[] bcHash = BCSM3Utils.hash(bigdata);
        log.info("bc hash: {}", CodecUtils.encodeBase64(bcHash));
        Assertions.assertEquals(CodecUtils.encodeBase64(bcHash), hashResp.getHash());
    }


}
