前端VUE后端JAVA,SM2加解密,一篇解决你的问题

一、后端JAVA

1、在pom.xml中添加

 <dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
</dependency>
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.68</version>
</dependency>
<!-- bcprov-jdk15 加密工具-->
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15to18</artifactId>
    <version>1.69</version>
</dependency>

2、sm2工具类

public class Sm2Util {
    //生成秘钥对
    public static MutablePair<String, String> createSM2Key(){
        SM2 sm2= SmUtil.sm2();
        sm2.setMode(SM2Engine.Mode.C1C3C2);
        String privateKey= HexUtil.encodeHexStr(BCUtil.encodeECPrivateKey(sm2.getPrivateKey()));
        String publicKey = HexUtil.encodeHexStr(((BCECPublicKey) sm2.getPublicKey()).getQ().getEncoded(false));
        return MutablePair.of(publicKey,privateKey);
    }

    //加密
    public static String encrypt(String data, String publicKey){
        String publicKeyTmp = publicKey;
        if (publicKey.length() == 130) {
            //这里需要去掉开始第一个字节 第一个字节表示标记
            publicKeyTmp = publicKey.substring(2);
        }
        String xhex = publicKeyTmp.substring(0, 64);
        String yhex = publicKeyTmp.substring(64, 128);
        ECPublicKeyParameters ecPublicKeyParameters = BCUtil.toSm2Params(xhex, yhex);
        //创建sm2 对象
        SM2 sm2 = new SM2(null, ecPublicKeyParameters);
        sm2.usePlainEncoding();
        sm2.setMode(SM2Engine.Mode.C1C3C2);
        return sm2.encryptHex(data, KeyType.PublicKey);

    }

    //解密
    public static String decrypt(String data, String privateKey){
        SM2 sm2 = new SM2(ECKeyUtil.toSm2PrivateParams(privateKey), null);
        sm2.setMode(SM2Engine.Mode.C1C3C2);
        sm2.setEncoding(new PlainDSAEncoding());
        String encryptStr = sm2.decryptStr(data, KeyType.PrivateKey);
        return encryptStr;
    }

二、前端VUE

1.安装依赖 gm-crypto

npm install gm-crypto

2.加解密方法

import { SM2} from "gm-crypto";
//加密方法
//plaintext为待加密数据
//publicKey 为加密公钥
const data =
      "04" +
      SM2.encrypt(plaintext, publicKey, {
        inputEncoding: "utf8",
        outputEncoding: "hex"
      });

//解密方法
// ciphertext :密文
// privateKey :解密私钥
data = SM2.decrypt(
      ciphertext.substring(2, ciphertext.length),
      privateKey,
      {
        inputEncoding: "hex",
        outputEncoding: "utf8"
      }
    );

三、避坑指南

1、后端加密后密文前两位为“04”,前端解密不了,所以在前端解密时要把“04”去掉,

2、前端加密后,密文没有“04”,所以前端加密完要在密文前面加上“04”