准备工作

后端(jar包)、前端(js文件)

阿里云盘:

所需文件: https://www.aliyundrive.com/s/reeVJUq2hXT


代码实现

后端


import com.antherd.smcrypto.sm2.Keypair;
import com.antherd.smcrypto.sm2.Sm2;
import io.netty.util.internal.StringUtil;

public class SM2Encryptor {
    /**
     * 加密,使用公钥
     *
     * @param publicKey
     * @param originalText
     * @return
     */
    public static String encryptText(String publicKey, String originalText) throws Exception {
        if (StringUtil.isNullOrEmpty(publicKey)) {
            throw new Exception("密钥不能为空...");
        }
        if (StringUtil.isNullOrEmpty(originalText)) {
            throw new Exception("明文不能为空...");
        }

        try {
            return Sm2.doEncrypt(originalText, publicKey);//HexUtil.encodeHexStr(cipherText); // 加密结果
        } catch (Exception e) {
            throw new Exception("加密错误:密钥不正确...");
        }
    }

    /**
     * 解密,使用私钥
     *
     * @param privateKey
     * @param cipherText
     * @return
     */
    public static String decryptText(String privateKey, String cipherText) throws Exception {
        if (StringUtil.isNullOrEmpty(privateKey)) {
            throw new Exception("密钥不能为空...");
        }
        if (StringUtil.isNullOrEmpty(cipherText)) {
            throw new Exception("明文不能为空...");
        }
        try {
            return Sm2.doDecrypt(cipherText, privateKey); // new String(sm2.decrypt(sourceData,prvKey)); // 解密结果
        } catch (Exception e) {
            throw new Exception("解密错误:密钥不正确...");
        }
    }

    /**
     * 获取sm2密钥对,
     *
     * @return 返回String[];第0个为公钥,第1个为私钥
     * @throws Exception
     */
    public static String[] generateKeyPair() throws Exception {
        try {
            Keypair keypair = Sm2.generateKeyPairHex();
            String[] result = new String[2];
            if (keypair != null) {
                result[0] = keypair.getPublicKey(); //公钥
                result[1] = keypair.getPrivateKey(); // 私钥
            }
            return result;
        } catch (Exception e) {
            throw new Exception("生成密钥对失败...");
        }
    }

    public static void main(String[] args) throws Exception {
        //生成一对 公钥与私钥
        String[] keys = generateKeyPair();
        //公钥
        String publicKey = keys[0];
        System.out.println("公钥" + publicKey);
        //私钥
        String privateKey = keys[1];
        System.out.println("私钥" + privateKey);

        String str = "测试使用SM2加密、解密";

        //加密字符串
        String encryptText = SM2Encryptor.encryptText(publicKey, str);
        System.out.println(encryptText);
        //解密字符串
        String decryptText = SM2Encryptor.decryptText(privateKey, encryptText);
        System.out.println(decryptText);

    }

}

输出结果
在这里插入图片描述


前端

<script>

    $(function () {
		//公钥
		var publicKey = "04bbfbea94e01445784544b29b9430a7b5309d6c93d0a05df2bfd43497f7f8de20cce0bf934f69e90ea399b372865899506a0abccd23a660dd191480014f2857cf";
    	//私钥
        var privateKey = "287eef8b13aeacd980427a902b20e9746f481258b06a2f30e8c0735b2efc6652";
		
		var str = "测试使用SM2加密、解密";
		
		//加密
		var encrText = sm2.doEncrypt(str ,publicKey);
		console.log(encrText)

       //解密
       var decryptText = sm2.doDecrypt(encrText,privateKey)
       console.log(decryptText)
     })
</script>

效果
在这里插入图片描述


** 特别注意 **

本次演示只是简单介绍前后端通用的加解密方式,学会之后我们可以灵活运用

1.前后端同时加解密,这样可以保障数据的安全

2.创建 公钥与私钥 的数据库,使用编号进行绑定公钥与私钥,这样可以通过编号找出对应的公钥与私钥(一个公钥对应唯一一个私钥)

3.发挥自己的想象和业务需求进行拓展、灵活运用…


以上就是前后端通用加密(sm2)的使用教程,有问题的小伙伴可以评论区或私信提出!

点赞收藏,以留备用!

我是xyushao!我们下期见!
在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐