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 EccPriKey {
    // 密 钥 位 长
    private int bits;
    // 私 钥
    private byte[] D;

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

    public static EccPriKey fromBytes(byte[] priKey) {
        Assert.notNull(priKey, "私钥数据不能为null");
        if (Objects.equals(priKey.length, 68)) {
            // 00010000
            priKey = Arrays.copyOfRange(priKey, 4, priKey.length);
        }
        Assert.isTrue(Objects.equals(priKey.length, 32) || Objects.equals(priKey.length, 64), "Ecc私钥数据格式错误");
        if (Objects.equals(priKey.length, 32)) {
            return new EccPriKey(256, priKey);
        }
        return new EccPriKey(256, Arrays.copyOfRange(priKey, 32, 64));
    }

}
