首先引入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);// trueboolean 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还有很多强大的工具类,方便程序员们的调用