package com.sunyard.chsm.sdf.model;

import com.sunyard.chsm.utils.CodecUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.Assert;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;

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

    // X 分量
    private byte[] x;
    // Y 分量
    private byte[] y;
    // 明文的 SM3 杂凑值
    private byte[] M;
    // 密文数据长度
    private int L;
    // 密文数据
    private byte[] C;

    public String getC1C3C2Hex() {
        return CodecUtils.encodeHex(getC1C3C2Bytes());
    }

    public byte[] getC1C3C2Bytes() {
        int xLen = x.length;
        int yLen = y.length;
        int mLen = M.length;

        byte[] rawData = new byte[xLen + yLen + mLen + L];

        System.arraycopy(x, 0, rawData, 0, xLen);
        System.arraycopy(y, 0, rawData, xLen, yLen);
        System.arraycopy(M, 0, rawData, xLen + yLen, mLen);
        System.arraycopy(C, 0, rawData, xLen + yLen + mLen, L);

        return rawData;
    }

    public byte[] toSdfData() {
        byte[] d = new byte[164 + L];
        byte[] l = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(L).array();
        System.arraycopy(x, 0, d, 32, 32);
        System.arraycopy(y, 0, d, 96, 32);
        System.arraycopy(M, 0, d, 128, 32);
        System.arraycopy(l, 0, d, 160, 4);
        System.arraycopy(C, 0, d, 164, L);
        return d;
    }

    public static EccCipher fromHex(String hex) {
        return fromBytes(CodecUtils.decodeHex(hex));
    }

    public static EccCipher fromBytes(byte[] cipher) {
        Assert.notNull(cipher, "Ecc密文数据不能为null");
        if (cipher[0] == 0x04) {
            cipher = Arrays.copyOfRange(cipher, 1, cipher.length);
        }
        Assert.isTrue(cipher.length > 96, "Ecc加密数据格式错误");
        if (cipher.length > 164
                && Arrays.equals(Arrays.copyOf(cipher, 32), new byte[32])
                && Arrays.equals(Arrays.copyOfRange(cipher, 64, 96), new byte[32])) {
            int L = cipher.length - 164;
            byte[] x = Arrays.copyOfRange(cipher, 32, 64);
            byte[] y = Arrays.copyOfRange(cipher, 96, 128);
            byte[] m = Arrays.copyOfRange(cipher, 128, 160);
            byte[] c = Arrays.copyOfRange(cipher, 164, cipher.length);
            return new EccCipher(x, y, m, L, c);
        }

        int L = cipher.length - 96;
        byte[] x = Arrays.copyOfRange(cipher, 0, 32);
        byte[] y = Arrays.copyOfRange(cipher, 32, 64);
        byte[] m = Arrays.copyOfRange(cipher, 64, 96);
        byte[] c = Arrays.copyOfRange(cipher, 96, cipher.length);
        return new EccCipher(x, y, m, L, c);
    }

}
