通过SM2 非对称加密、解密

SM2通过椭圆曲线进行加密
引入依赖 (SM2可能有其他依赖也有同名类,引入其他依赖导致启动报错。如:pay1pay-rsa,需要进行exclusion)

<dependency>
    <groupId>org.bouncycastlegroupId>
    <artifactId>bcprov-jdk15onartifactId>
    <version>1.68version>
    <scope>testscope>
dependency>
<dependency>
    <groupId>cn.hutoolgroupId>
    <artifactId>hutool-allartifactId>
    <version>5.7.10version>
    <scope>testscope>
dependency>

通过单元测试,进行加、解密

import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import com.alibaba.fastjson.JSONObject; 

@Test
 public void test8() {
     SM2 sm = SmUtil.sm2();
     String privateKeyBase64 = sm.getPrivateKeyBase64();
     String publicKeyBase64 = sm.getPublicKeyBase64();
     System.out.println("密钥"+privateKeyBase64);
     System.out.println("公钥"+publicKeyBase64);
     // 需要加密内容
     String a = "abcde";
     // 通过公钥进行加密
     SM2 sm2 = SmUtil.sm2(null, publicKeyBase64);
     String encryptStr = sm2.encryptBase64(a, KeyType.PublicKey);
     System.out.println("加密后报文"+ encryptStr);

     // 通过密钥解密
     SM2 sm22 = SmUtil.sm2(privateKeyBase64, null);
     String s = sm22.decryptStr(encryptStr, KeyType.PrivateKey);
     System.out.println("解密后报文"+ s);
 }

打印结果

密钥MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQg40TGMKM0+NYF1YQIHA+5CKraDJSX4DEeKl6J2XV5pOWgCgYIKoEcz1UBgi2hRANCAASVxiwIr/YEfNvBuvBqZWqAel+PH/CO0FMn409+XLUEC/8HL47+fzMkBTIVYYUsgm7ssWmU7JzZYreYCYf+79jR
公钥MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAElcYsCK/2BHzbwbrwamVqgHpfjx/wjtBTJ+NPfly1BAv/By+O/n8zJAUyFWGFLIJu7LFplOyc2WK3mAmH/u/Y0Q==
加密后报文BHz5g6ECBF88/+oVNGbekT4ISVVh1jzp4AfFAKjU0uQmqOE1acQ7WhKW8DKCmXQyWQznKOGNx4roGTLYo/6VuPRYK5IzOQ2MzVZX4BiECOhBCVctk5NlsTtgxUKM9JZ7+8aQ6kb0
解密后报文abcde

你可能感兴趣的:(代码功能,java,加密解密)