引入pom依赖

 <dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>30.1.1-jre</version>
</dependency>
<dependency><groupId>org.bouncycastle</groupId><artifactId>bcprov-jdk15on</artifactId><version>1.70</version>
</dependency>

java SM2加解密工具类:

package com.tool;import com.google.common.base.Preconditions;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.crypto.signers.SM2Signer;
import org.bouncycastle.jcajce.provider.asymmetric.util.ECUtil;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.util.Base64Utils;import java.security.*;
import java.security.spec.*;public class SM2Util {private static final SM2Engine.Mode DIGEST = SM2Engine.Mode.C1C3C2;private static final String ALGORITHM = "SM2";/*** 私钥转换为 {@link ECPrivateKeyParameters}* @param key key* @return* @throws InvalidKeyException*/public static ECPrivateKeyParameters privateKeyToParams(String algorithm, byte[] key) throws InvalidKeyException, InvalidKeySpecException, NoSuchAlgorithmException {Preconditions.checkNotNull(key, "key must be not null !");PrivateKey privateKey = generatePrivateKey(algorithm, key);return (ECPrivateKeyParameters) ECUtil.generatePrivateKeyParameter(privateKey);}/*** 生成私钥* @param algorithm 算法* @param key       key* @return*/public static PrivateKey generatePrivateKey(String algorithm, byte[] key) throws NoSuchAlgorithmException, InvalidKeySpecException {Preconditions.checkNotNull(algorithm, "algorithm must be not null !");Preconditions.checkNotNull(key, "key must be not null !");KeySpec keySpec = new PKCS8EncodedKeySpec(key);algorithm = getAlgorithmAfterWith(algorithm);return getKeyFactory(algorithm).generatePrivate(keySpec);}/*** 公钥转换为 {@link ECPublicKeyParameters}* @param key key* @return* @throws InvalidKeyException*/public static ECPublicKeyParameters publicKeyToParams(String algorithm, byte[] key) throws InvalidKeyException, InvalidKeySpecException, NoSuchAlgorithmException {Preconditions.checkNotNull(key, "key must be not null !");PublicKey publicKey = generatePublicKey(algorithm, key);return (ECPublicKeyParameters) ECUtil.generatePublicKeyParameter(publicKey);}/*** 生成公钥* @param algorithm 算法* @param key       key* @return*/public static PublicKey generatePublicKey(String algorithm, byte[] key) throws NoSuchAlgorithmException, InvalidKeySpecException {Preconditions.checkNotNull(algorithm, "algorithm must be not null !");Preconditions.checkNotNull(key, "key must be not null !");KeySpec keySpec = new X509EncodedKeySpec(key);algorithm = getAlgorithmAfterWith(algorithm);return getKeyFactory(algorithm).generatePublic(keySpec);}/*** 获取用于密钥生成的算法<br>* 获取XXXwithXXX算法的后半部分算法,如果为ECDSA或SM2,返回算法为EC* @param algorithm XXXwithXXX算法* @return 算法*/private static String getAlgorithmAfterWith(String algorithm) {Preconditions.checkNotNull(algorithm, "algorithm must be not null !");int indexOfWith = StringUtils.lastIndexOfIgnoreCase(algorithm, "with");if (indexOfWith > 0) {algorithm = StringUtils.substring(algorithm, indexOfWith + "with".length());}if ("ECDSA".equalsIgnoreCase(algorithm) || ALGORITHM.equalsIgnoreCase(algorithm)) {algorithm = "EC";}return algorithm;}/*** 获取{@link KeyFactory}* @param algorithm 非对称加密算法* @return {@link KeyFactory}*/private static KeyFactory getKeyFactory(String algorithm) throws NoSuchAlgorithmException {final Provider provider = new BouncyCastleProvider();return KeyFactory.getInstance(algorithm, provider);}/*** 加密* @param data      数据* @param publicKey 公钥* @return 加密之后的数据*/public static byte[] encrypt(byte[] data, byte[] publicKey) throws Exception {CipherParameters pubKeyParameters = new ParametersWithRandom(publicKeyToParams(ALGORITHM, publicKey));SM2Engine engine = new SM2Engine(DIGEST);engine.init(true, pubKeyParameters);return engine.processBlock(data, 0, data.length);}/*** 解密* @param data       数据* @param privateKey 私钥* @return 解密之后的数据*/public static byte[] decrypt(byte[] data, byte[] privateKey) throws Exception {CipherParameters privateKeyParameters = privateKeyToParams(ALGORITHM, privateKey);SM2Engine engine = new SM2Engine(DIGEST);engine.init(false, privateKeyParameters);byte[] byteDate = engine.processBlock(data, 0, data.length);return byteDate;}/*** 签名* @param data 数据* @return 签名*/public static byte[] sign(byte[] data, byte[] privateKey) throws Exception {SM2Signer signer = new SM2Signer();CipherParameters param = new ParametersWithRandom(privateKeyToParams(ALGORITHM, privateKey));signer.init(true, param);signer.update(data, 0, data.length);return signer.generateSignature();}/*** 用公钥检验数字签名的合法性* @param data      数据* @param sign      签名* @param publicKey 公钥* @return 是否验证通过*/public static boolean verify(byte[] data, byte[] sign, byte[] publicKey) throws Exception {SM2Signer signer = new SM2Signer();CipherParameters param = publicKeyToParams(ALGORITHM, publicKey);signer.init(false, param);signer.update(data, 0, data.length);return signer.verifySignature(sign);}/*** 生成公钥和私钥* @return* @throws Exception*/public static KeyPair generateSm2KeyPair(){//使用标准名称创建EC参数生成的参数规范final ECGenParameterSpec sm2Spec = new ECGenParameterSpec("sm2p256v1");// 获取一个椭圆曲线类型的密钥对生成器final KeyPairGenerator kpg;try {kpg = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());// 使用SM2算法域参数集初始化密钥生成器(默认使用以最高优先级安装的提供者的 SecureRandom 的实现作为随机源)// kpg.initialize(sm2Spec);// 使用SM2的算法域参数集和指定的随机源初始化密钥生成器kpg.initialize(sm2Spec, new SecureRandom());// 通过密钥生成器生成密钥对return kpg.generateKeyPair();} catch (Exception e) {e.printStackTrace();return null;}}public static void main(String[] args) throws Exception {KeyPair keyPair = generateSm2KeyPair();//明文String plaintext = "test";//加密byte[] ciphertext = Base64Utils.encode(encrypt(plaintext.getBytes("utf-8"), keyPair.getPublic().getEncoded()));//生成签名byte[] signature = Base64Utils.encode(sign(plaintext.getBytes("utf-8"),keyPair.getPrivate().getEncoded()));System.out.println("ciphertext: " + new String(ciphertext));System.out.println("signature: " + new String(signature));//解密plaintext = new String(decrypt(Base64Utils.decode(ciphertext),keyPair.getPrivate().getEncoded()),"utf-8");//验签boolean result = verify(plaintext.getBytes("utf-8"),Base64Utils.decode(signature),keyPair.getPublic().getEncoded());System.out.println("plaintext: " + plaintext);System.out.println("verify result: " + result);}
}

SM2 生成公钥私钥 签名 加解密 亲测可用相关推荐

  1. 在openssl中对SM2的公私钥进行加解密的验证

    在上一篇文章中<通过openssl生成sm2的公私钥的方法>介绍了如何在openssl系统中生成公私钥对,如何对生成的公私钥对进行验证呢? 在ecparam.c中,添加加解密的代码就可以了 ...

  2. PHP RSA 生成公钥私钥 PSA2 加密解密

    阅读目录 一.[PHP]生成 RSA 公钥私钥 二.[PHP]RSA2 签名与验签的使用类 1.php RSA2 签名 2.php RSA2 验签 三.[PHP]RSA2 加密算法的方法 1 使用公钥 ...

  3. 自签名多级证书亲测可用

    rem 不能使用jdk1.7 set JAVA_HOME=E:\tools\java\jdk1.8.0_181x64 set PATH=%JAVA_HOME%\bin;%PATH% cd E:\编程技 ...

  4. 微信小程序码的生成(JAVA完整版) 亲测可用

    JAVA生成小程序码(太阳码) 首先准备工具类,这里我使用的是QrUtil;废话不多说,上工具类; 工具类是获取token使用; appid = 小程序appID secret = 小程序秘钥 /** ...

  5. 分享一个RSA加解密工具类,公钥加密私钥解密、私钥加密公钥解密、私钥签名公钥验签、生成公钥私钥

    测试: public static void main(String[] args) {try {//生成公钥私钥Map<String, Object> map = RSAUtil.ini ...

  6. 学习笔记:公钥私钥 签名验签 加密解密 CA 证书

    重点: 1.区分加密解密和签名验签(在非对称加密情景下) 加密解密:#A给B发消息# A用B的公钥进行运算(加密),B收到后用B自己的私钥进行逆向运算(解密) 签名验签:#A给B发消息# A用A自己的 ...

  7. 国产sm2,sm3,sm4加解密

    有个为国家做的项目,其中需求是必须要用国产的加密,最后经项目组讨论后决定用国产sm2加密 本人用vue开发前端所以一下实在vue中用的方法, 国密相关介绍 国密算法是国家密码局制定标准的一系列算法,主 ...

  8. 公钥 私钥_公钥 私钥 签名 验签 说的啥?

    公钥 私钥 签名 验签 说的啥? 公钥加密,私钥解密 私钥签名,公钥验签 散列算法 散列算法,也叫做哈希函数,是从一个任何一种数据中创建小的数字方法,散列函数把消息或者数据压缩成摘要,有时候也叫做摘要 ...

  9. php如何生成公钥私钥,php如何生成公钥私钥(代码)

    本篇文章给大家带来的内容是关于php如何生成公钥私钥(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. //http://www.lampol-blog.com/detail/a ...

最新文章

  1. linux查看文件安全权限,Linux系统下如何查看及修改文件读写权限
  2. 跳表(skipList)
  3. java中JOptionPane类_java:JOptionPane类消息框总结
  4. Python os.chdir() 方法
  5. Python笔记 【无序】 【五】
  6. SAP License:SAP概念辨识
  7. zookeeper观察者模式设计实例
  8. 关于理财、专户、基金与避税
  9. java lame_音视频编解码——LAME
  10. 成都锦里VS宽窄巷子
  11. android rom 制作工具,ROM工具箱(ROM Toolbox Pro)
  12. 我国影视行业的痛点——影视链的目标
  13. lio linux工具,Linux中三种SCSI target的介绍之LIO
  14. 程序猿的自救 从零备考NSCA/CSCS 1 身体系统的构造与系统
  15. css好看常用的中文字体
  16. ArcFaceSDK3.0 Python Demo
  17. python怎么输出图像测试_【Python】使用Pytest集成Allure生成漂亮的图形测试报告
  18. 纯css3实现圆环占比图
  19. 三星服务器链接在哪个文件夹,三星手机无线连接,访问局域网电脑共享目录中的电影照片设置教程...
  20. Proxy Switchysharp配置

热门文章

  1. JSOI2019招待
  2. c语言 log4c,LOG4C 的使用
  3. 给世界上色——滤镜底层原理
  4. 慧都APS解决方案,点亮「照明灯具行业」精益化生产之路
  5. npm install时cb() never called!错误解决方法
  6. Unity踩坑:FindObjectsOfType can only be called from the main thread
  7. 史上最完美的 Typora 教程
  8. PSV 黑商店 pkgj 无法刷新列表 显示HttpError 的解决办法
  9. float 与 double 的区别
  10. Linux系统中用命令行清空垃圾箱Trash