国密sm2公钥加密 私钥解密java代码实现

时间:2025-03-28 13:09:40

目录

一、引入jar包

二、生成秘钥对,加解密工具类


一、引入jar包

        <!-- sm2加密依赖 -->
        <dependency>
            <groupId></groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.70</version>
        </dependency>

二、生成秘钥对,加解密工具类

import .Base64;
import ;
import .SM2Engine;
import ;
import ;
import ;
import ;
import org.;
import org.;
import .*;
import ;
import .PKCS8EncodedKeySpec;
import .X509EncodedKeySpec;


/**
 * @ClassName
 * @Description 加密工具类
 * @Author csn
 * @Date 14:54 2022/11/14
 * @Version V1.0
 **/
public class PassUtils {
    private static Logger logger = ();

    private static final  DIGEST = .C1C3C2;


    /**
     * @Description: 生成sm2秘钥对
     * @Author: csn
     * @date: 2022/11/14
     */
    public static KeyPair createSm2Key() {
        try {
            //使用标准名称创建EC参数生成的参数规范
            final ECGenParameterSpec sm2p256v1 = new ECGenParameterSpec("sm2p256v1");
            // 获取一个椭圆曲线类型的密钥对生成器
            final KeyPairGenerator kpg = ("EC", new BouncyCastleProvider());
            // 使用SM2的算法区域初始化密钥生成器
            (sm2p256v1, new SecureRandom());
            // 获取密钥对
            return ();
        } catch (Exception e) {
            ("生成秘钥对失败{}", ());
            return null;
        }
    }

    /**
     * sm2公钥加密方法
     * @param publicKeyStr 加密的公钥
     * @param data         需要加密的数据
     * @return 返回加密后的字符串
     */
    public static String encryptSm2(String publicKeyStr, String data) {
        try {
            //算法工具包
            (new BouncyCastleProvider());
            //将公钥字符串转为公钥字节
            byte[] bytes = Base64.decodeBase64(publicKeyStr);
            KeyFactory keyFactory = ("EC", BouncyCastleProvider.PROVIDER_NAME);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
            ("获取转换后的公钥");
            PublicKey publicKey = (keySpec);

            ("开始加密");
            CipherParameters pubKeyParameters = new ParametersWithRandom((publicKey), new SecureRandom());
            SM2Engine sm2Engine = new SM2Engine();
            (true, pubKeyParameters);
            byte[] arrayBytes = ((), 0, ().length);
            return Base64.encodeBase64String(arrayBytes);
            //开始加密
        } catch (Exception e) {
            ("加密失败{}", ());
        }
        return null;

    }

    /**
     * sm2私钥解密方法
     * @param privateStr 私钥
     * @param data       需要解密的数据
     * @return 返回解密后的数据
     */
    public static String decryptSm2(String privateStr, String data) {
        try {
            ("私钥转换");
            byte[] bytes = Base64.decodeBase64(privateStr);
            KeyFactory keyFactory = ("EC", BouncyCastleProvider.PROVIDER_NAME);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
            PrivateKey privateKey = (keySpec);
            ("sm2开始解密");

            CipherParameters privateKeyParameters = ((BCECPrivateKey) privateKey);
            SM2Engine engine = new SM2Engine();
            (false, privateKeyParameters);
            byte[] byteDate = (Base64.decodeBase64(data), 0, Base64.decodeBase64(data).length);
            return new String(byteDate);
        } catch (Exception e) {
            ("sm2解密失败{}", ());
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        //定义需要加密的字符串
        String str = "aaaaa";
        //生成秘钥对
        KeyPair sm2Key = createSm2Key();
        //获取公钥
        PublicKey publicKey = ();
        //获取公钥base加密后字符串
        String publicStr = Base64.encodeBase64String(());
        ("公钥为:{}", publicStr);
        //获取私钥
        PrivateKey privateKey = ();
        //获取私钥base加密后字符串
        String privateStr = Base64.encodeBase64String(());
        ("私钥为:{}", privateStr);

        //公钥加密
        String passStr = encryptSm2(publicStr, str);
        ("加密后为{}", passStr);
        //私钥解密
        String deStr = decryptSm2(privateStr, passStr);
        ("解密后为{}", deStr);
    }
}