java生成sm2使用hutool生成公钥私钥

首先引入maven依赖

<dependency>
  <groupId>org.bouncycastle</groupId>
  <artifactId>bcprov-jdk15to18</artifactId>
  <version>1.69</version>
</dependency>
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.16</version>
</dependency>

然后运行以下代码

KeyPair pair = SecureUtil.generateKeyPair("SM2");
byte[] privateKey = pair.getPrivate().getEncoded();
byte[] publicKey = pair.getPublic().getEncoded();
//私钥
String privateKeyStr=Base64.getEncoder().encodeToString(privateKey);
//公钥
String publicKeyStr=Base64.getEncoder().encodeToString(publicKey);

就可以得到私钥和公钥

公钥提供给通讯方验签

下面是签名的代码

String content = "我是Hanley.";
final SM2 sm2 = SmUtil.sm2(privateKeyStr,null);
String sign = sm2.signHex(HexUtil.encodeHexStr(content));

验签代码

final SM2 sm2 = SmUtil.sm2(null,publicKeyStr);
// true
boolean verify = sm2.verifyHex(HexUtil.encodeHexStr(content), sign);

加密

// 公钥加密,私钥解密
SM2 sm2 = SmUtil.sm2(null, publicKey);
String encryptStr = sm2.encryptBcd(text, KeyType.PublicKey);

解密

// 公钥加密,私钥解密
SM2 sm2 = SmUtil.sm2(privateKeyStr, null);
String decryptStr = StrUtil.utf8Str(sm2.decryptFromBcd(encryptStr, KeyType.PrivateKey));

好了,以上就是sm2util的使用介绍了,hutool还有很多强大的工具类,方便程序员们的调用

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值