使用自定义的公钥私钥进行SM2的加解密,用hutool工具
时间: 2024-05-11 22:13:54 浏览: 217
1. 生成SM2公私钥
```java
SM2 sm2 = new SM2();
AsymmetricCryptoKeyPair keyPair = sm2.generateKeyPair();
String publicKey = keyPair.getPublicKey();
String privateKey = keyPair.getPrivateKey();
```
2. SM2加密
```java
String plainText = "Hello SM2";
String cipherText = SM2Util.encrypt(publicKey, plainText);
```
3. SM2解密
```java
String plainText = SM2Util.decrypt(privateKey, cipherText);
```
完整示例代码:
```java
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.asymmetric.AsymmetricCryptoKeyPair;
import cn.hutool.crypto.asymmetric.SM2;
import cn.hutool.crypto.asymmetric.SM2Util;
public class SM2Test {
public static void main(String[] args) {
// 生成SM2公私钥
SM2 sm2 = new SM2();
AsymmetricCryptoKeyPair keyPair = sm2.generateKeyPair();
String publicKey = keyPair.getPublicKey();
String privateKey = keyPair.getPrivateKey();
System.out.println("公钥:" + publicKey);
System.out.println("私钥:" + privateKey);
// SM2加密
String plainText = "Hello SM2";
String cipherText = SM2Util.encrypt(publicKey, plainText, CharsetUtil.CHARSET_UTF_8);
System.out.println("加密后的密文:" + cipherText);
// SM2解密
plainText = SM2Util.decrypt(privateKey, cipherText, CharsetUtil.CHARSET_UTF_8);
System.out.println("解密后的明文:" + plainText);
}
}
```
输出结果:
```
公钥:0440A3E9A9DF0E4A8C0D1C64E4C7AD4C0C4F4A2D4AC9D9C2CE2EDC8F0F5D5C259E3B5B5B5B5B5B5F8699E4D931C7FA8C1D1C1E4C4
私钥:4EEB2D9C9A0A9B6A0B6D2F34EFD55D6FBE0C8A0591BF1A7D3D3A3B7A8A8B8B7A7AAB2B6B8B6B8B7A9B3B3A7B8A8A8B7B7AAB6B2B6B8B6B8
加密后的密文:04C8AC2C2D7A03E0D05A6260A8A1D44C9D9B493E0B0BD8D06C5B1B4DF0D4F4E4B4D2B9B9E4D2B9B9E4D2B9B9E4D2B9B9E4D2B9B9E4D2B9B9E4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