package com.jiayue.ssi.service;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.BCUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.SM2;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;

/**
* 生成sm2密钥
*
* @author xsl
* @since 2023/02/28
*/
public class CreateSm2Key {
    public static void main(String[] args) {
        SM2 sm = SmUtil.sm2();

        // sm2的加解密时有两种方式即 C1C2C3、 C1C3C2，
        sm.setMode(SM2Engine.Mode.C1C3C2);

        // 生成私钥
        String privateKey = HexUtil.encodeHexStr(sm.getPrivateKey().getEncoded());
        System.out.println("私钥:"+ privateKey);
        // 生成公钥
        String publicKey = HexUtil.encodeHexStr(sm.getPublicKey().getEncoded());
        System.out.println("公钥:"+ publicKey);
        // 生成私钥D
        String privateKeyD = HexUtil.encodeHexStr(BCUtil.encodeECPrivateKey(sm.getPrivateKey())); // ((BCECPrivateKey) privateKey).getD().toByteArray();
        System.out.println("私钥D:"+ privateKeyD);
        // 生成公钥Q，以q值做为js端的加密公钥
        String publicKeyQ = HexUtil.encodeHexStr(((BCECPublicKey) sm.getPublicKey()).getQ().getEncoded(false));
        System.out.println("公钥Q:"+ publicKeyQ);
    }
}
