package com.yida.data.common.core.utils.construction;

import java.security.*;

/**
 * RSASig类
 *
 * @author ZYJ
 * @date 2023/6/22 2:22
 */
public class RSASig {

    private String pubKey;
    private static final char[] bcdLookup = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public RSASig() {
    }

    public String getPublicKey() {
        return this.pubKey;
    }

    public void setPublicKey(String pkey) {
        this.pubKey = pkey;
    }

    public boolean verifySignature(String sign, String src) {
        try {
            Security.addProvider(new ABAProvider());
            Signature sigEng = Signature.getInstance("MD5withRSA", "ABA");
            byte[] pubByte = hexStrToBytes(this.pubKey.trim());
            sigEng.initVerify(new RSAPubKey(pubByte));
            sigEng.update(src.getBytes());
            byte[] sign1 = hexStrToBytes(sign);
            return sigEng.verify(sign1);
        } catch (Exception var6) {
            return false;
        }
    }

    public static final String bytesToHexStr(byte[] bcd) {
        StringBuffer s = new StringBuffer(bcd.length * 2);

        for(int i = 0; i < bcd.length; ++i) {
            s.append(bcdLookup[bcd[i] >>> 4 & 15]);
            s.append(bcdLookup[bcd[i] & 15]);
        }

        return s.toString();
    }

    public static final byte[] hexStrToBytes(String s) {
        byte[] bytes = new byte[s.length() / 2];

        for(int i = 0; i < bytes.length; ++i) {
            bytes[i] = (byte)Integer.parseInt(s.substring(2 * i, 2 * i + 2), 16);
        }

        return bytes;
    }

}
