package com.sunyard.chsm.sdf.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.bouncycastle.util.encoders.Hex;
import org.springframework.util.Assert;

import java.util.Arrays;
import java.util.Objects;

/**
 * @author liulu
 * @version V1.0
 * @since 2022/11/11
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class EccPubKey {
    // 密 钥 位 长
    private int bits;
    // 公 钥 x 坐 标
    private byte[] x;
    // 公 钥 y 坐 标
    private byte[] y;

    public String getPubKeyHex() {
        return Hex.toHexString(getPubKeyBytes());
    }

    public byte[] getPubKeyBytes() {
        byte[] rawKey = new byte[x.length + y.length];
        System.arraycopy(x, 0, rawKey, 0, x.length);
        System.arraycopy(y, 0, rawKey, x.length, y.length);
        return rawKey;
    }

    public byte[] toSdfData() {
        byte[] sdf = new byte[132];
        System.arraycopy(Hex.decode("00010000"), 0, sdf, 0, 4);
        System.arraycopy(x, 0, sdf, 36, 32);
        System.arraycopy(y, 0, sdf, 100, 32);
        return sdf;
    }

    public static EccPubKey fromHex(String pubKeyHex) {
        return fromBytes(Hex.decode(pubKeyHex));
    }

    public static EccPubKey fromBytes(byte[] pubKey) {
        Assert.notNull(pubKey, "公钥数据不能为null");
        if (Objects.equals(pubKey.length, 65)) {
            Assert.isTrue(Objects.equals(pubKey[0], 0x04), "Ecc公钥数据格式错误,必须04开头");
            pubKey = Arrays.copyOfRange(pubKey, 1, pubKey.length);
        } else if (Objects.equals(pubKey.length, 132)) {
            // 00010000
            pubKey = Arrays.copyOfRange(pubKey, 4, pubKey.length);
        }
        Assert.isTrue(Objects.equals(pubKey.length, 64) || Objects.equals(pubKey.length, 128), "Ecc公钥数据格式错误");
        byte[] x = new byte[32];
        byte[] y = new byte[32];
        if (Objects.equals(pubKey.length, 64)) {
            System.arraycopy(pubKey, 0, x, 0, 32);
            System.arraycopy(pubKey, 32, y, 0, 32);
        } else if (Objects.equals(pubKey.length, 128)) {
            System.arraycopy(pubKey, 32, x, 0, 32);
            System.arraycopy(pubKey, 96, y, 0, 32);
        }
        return new EccPubKey(256, x, y);
    }

}
