package com.crm.pay.utils;

import com.crm.rely.backend.util.HexUtil;
import org.bitcoinj.base.Sha256Hash;
import org.bitcoinj.crypto.ECKey;
import org.bitcoinj.crypto.SignatureDecodeException;

/**
 * @Author houn
 * @Date 2024/4/25 00:49
 * @PackageName:com.crm.pay.utils
 * @ClassName: BitcoinjECDSAUtil
 * @Description: TODO
 */
public class BitcoinjECDSAUtil {
    public static String sign(String priKey, String content) {

        return sign(HexUtil.decode(priKey), content);
    }

    public static String sign(byte[] priKey, String content) {
        ECKey eckey = ECKey.fromPrivate(priKey);

        return HexUtil.bytes2Hex(eckey.sign(Sha256Hash.wrap(doubleSha256(content))).encodeToDER());
    }

    public static boolean verify(String pubKey, String content, String sign) throws SignatureDecodeException {
        ECKey eckey = ECKey.fromPublicOnly(HexUtil.decode(pubKey));

        return eckey.verify(doubleSha256(content), HexUtil.decode(sign));
    }

    private static byte[] doubleSha256(String content) {
        return Sha256Hash.hashTwice(content.getBytes());
    }

    public static void getECKey() {
        ECKey key = new ECKey();


        System.out.println("private key: " + HexUtil.bytes2Hex(key.getPrivKeyBytes()) + "; public key: " + HexUtil.bytes2Hex(key
                .getPubKey()));
    }


    public static void main(String[] args) throws SignatureDecodeException {
        getECKey();

//        System.out.println(sign("513f4a84396b26790c6605941ed4ea3176c492e300c6e2e2d635a7c3a54af217", "POST|/v1/api" +
//                "/order/create/buy|1714020483755|area_code=%2B86&callback_url=https" +
//                "%3A" +
//                "%2F%2Ftestpay.cwgvu.com%2Fxpay%2Fcallback&coin_amount=10&coin_name=USDT&email=aldfjlasdj%40test" +
//                ".com&kyc_card_num=350124197902112916&kyc_id_card_type=1&kyc_name=zhang+san&legal_currency=CNY" +
//                "&legal_currency_amount=65&merchant_order_no=PD202404251248036163_66753851&price_timestamp" +
//                "=1714020483755&return_url=https%3A%2F%2Ftestpay.cwgvu.com%2Fxpay%2Fpickup"));
//        System.out.println(verify("0383205111f115e81776518ddf5ed02a5753319135742eb2d8bcee0a24dae3c949", "123", sign(
//                "1cec5f72cc11c5cc83b43e3154921176629c33205c638bf6b985dcd528834a17", "123")));

    }

}
