package com.sunyard.chsm.sdf.model;

import com.sunyard.chsm.utils.CodecUtils;
import com.sunyard.chsm.utils.gm.BCSM2Utils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.util.Arrays;

/**
 * @author liulu
 * @version V1.0
 * @since 2022/11/11
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class EccSignature {

    // 签名的 r 部分
    private byte[] r;

    // 签名的 s 部分
    private byte[] s;


    public String getRawSignHex() {
        return CodecUtils.encodeHex(getRawSignBytes());
    }

    public byte[] getDerSignBytes() {
        try {
            return BCSM2Utils.encodeSM2SignToDER(getRawSignBytes());
        } catch (IOException e) {
            throw new IllegalArgumentException("ECC签名数据格式错误");
        }
    }

    public byte[] getRawSignBytes() {
        byte[] signData = new byte[r.length + s.length];
        System.arraycopy(r, 0, signData, 0, r.length);
        System.arraycopy(s, 0, signData, r.length, s.length);
        return signData;
    }

    public byte[] toSdfData() {
        byte[] res = new byte[128];
        System.arraycopy(r, 0, res, 32, 32);
        System.arraycopy(s, 0, res, 96, 32);
        return res;
    }

    public static EccSignature fromBytes(byte[] sign) {
        if (sign == null || sign.length == 0) {
            throw new IllegalArgumentException("ECC签名数据格式错误");
        }
        if (sign.length >= 70 && sign.length <= 75) {
            sign = BCSM2Utils.decodeDERSM2Sign(sign);
        }

        if (sign.length == 64) {
            byte[] r = Arrays.copyOfRange(sign, 0, 32);
            byte[] s = Arrays.copyOfRange(sign, 32, 64);
            return new EccSignature(r, s);
        } else if (sign.length == 128) {
            byte[] r = Arrays.copyOfRange(sign, 32, 64);
            byte[] s = Arrays.copyOfRange(sign, 96, 128);
            return new EccSignature(r, s);
        } else {
            throw new IllegalArgumentException("ECC签名数据格式错误");
        }
    }

}
