若依基于sm-crypto实现前后端登录密码加密

发布时间:2024年01月13日

上一节介绍了基于jsencrypt实现的密码加密解密登录功能,这次来介绍基于sm-crypto实现前后端登录密码加密,本次采用的是sm2进行的加密解密。

后端

首先从后端代码开始写起(因为公钥和私钥都是要从java代码中生成):
首先需要引入sm-crypto的jar包,点击获取jar包,然后拷贝到下面的目录下
在这里插入图片描述
然后再pom.xml文件中引入依赖,然后刷新依赖

        <!--sm2jar包依赖-->
        <dependency>
            <groupId>com.sm2</groupId>
            <artifactId>sm2</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${basedir}/src/main/resources/lib/sm-crypto-0.3.2.jar</systemPath>
        </dependency>

然后就是新建一个工具类

package com.ruoyi.common.utils.sm2Encrypt;

import com.antherd.smcrypto.sm2.Keypair;
import com.antherd.smcrypto.sm2.Sm2;
import io.netty.util.internal.StringUtil;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

@Component
public class SM2Encryptor {

    private static final SmKeyPair smKeyPair = new SmKeyPair();
    public static String privateKeys = "";
    private static String publicKeyStr = "";
    private static String privateKeyStr = "92b704fee9ac448ac27abfa537021ab42d0035151f01fdc03e49b0c2f5496148";

    /**
     * 加密,使用公钥
     *
     * @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("加密错误:密钥不正确...");
        }
    }

    public static String getPublicKey() {
        return publicKeyStr;
    }

    public static String getPrivateKey() {
        return privateKeyStr;
    }

    public static SmKeyPair smKeyPair() {
        return smKeyPair;
    }

    /**
     * 解密,使用私钥
     *
     * @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 {
			String s = Sm2.doDecrypt(cipherText, privateKey);
            System.out.println(s);
            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(); //公钥
                smKeyPair.setPublicKey(keypair.getPublicKey());
                publicKeyStr = keypair.getPublicKey();
                result[1] = keypair.getPrivateKey(); // 私钥
                smKeyPair.setPrivateKey(keypair.getPrivateKey());
                privateKeyStr = 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];
//		String publicKey = publicKeyStr;
        System.out.println("公钥" + publicKey);
//		私钥
        String privateKey = privateKeyStr;
        System.out.println("私钥" + privateKey);

//		String str = "测试使用SM2加密、解密";
        String str = "166ed3fc69afcfee4f1ba2034c36dac93d86dcad176219407776100130a506d9";
        try {
            //加密字符串
            String encryptText = SM2Encryptor.encryptText(publicKey, str);
            System.out.println(encryptText);
        } catch (Exception e) {


        }


        //解密字符串
        String decryptText = "null";
        try {
            decryptText = SM2Encryptor.decryptText("", str);
            System.out.println("成功解密后为:"+decryptText);
        } catch (Exception e) {
            System.out.println("失败");
        }


    }

    public static void main11(String[] args) throws Exception {
        ArrayList<String> strings = new ArrayList<>();
        String str = ("$2a$10$0OXfRm8Jc4XdRFHeXFovB.UKX2DjLfgPYYS/6mz7K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Hf6pyr.uVQCYJYqrOZLnfe9BqLG,$2a$10$f02b1NTFiPBGWVwyMOyMw.g7xVq1hsegBpPdoi0afT17PqNrLOaba,"+
                "$2a$10$WS4zO1Odf0pa2S3SB0UDbObR5tVQWnql6XnXrnxSjGdasq24kx9VG,$2a$10$xPhPCcYIZO0UFJMnkl8ZW.30wgfc494IdUSKu6/DP3Z7GnqOxZ1By,$2a$10$.yLwueJ/xQueMcH3qa55eOBPjWJDB0oBLS3F3VGY8il8zvoft6EJu,$2a$10$Nx8pouYgkoBSCz86uEcvn.ExNQNaXIStSqB3fsNfbdP5Oj47zx4Ra,$2a$10$u3cFkCt2qgpYMMewjAuBm.C.FFvBjMSr0VaI6r1e8epInmvNpEbBy,$2a$10$vV7cPypCsNemcD9ZiQrNG.bUskbxKzzz73t4Fnq5UoRPQGtFSQePq,$2a$10$OKb.aK9Ofb/cEMHYvjWFwuu.CdFwby15ZdyetNwGUKxRMYLmZNk52,$2a$10$WarCwyP5JWp2Rrc4xC3CUex1FKRX4bY62fSj..tUd8PmlHxF8I82G,"+
                "$2a$10$y/JUE6C7NPnTuZjJWnMW1u7VRfeFbn18kB1HK1H1yT5cxQbJcvgIW,$2a$10$f1DBVIc1CQWVbZAY1zsk4OMS7ovVOPF8fzb9J4oUSpJ5tl5PLlOJe,$2a$10$OsgtQDRgQ0Qqnc0m/Oe3g.Fac6/6MmoFd7YIa38Jm8MiywlcvhrVG,$2a$10$2YkCgG9I6I/ihqW0mdzMKuSgntMiqfIN128ynjm/fJkMJCcaK7Ae.,$2a$10$tDKZGVoIk9bmsB8Zta4DweuPSG4gwzNHG5nqL/tONWqewKSmVPrYW,$2a$10$zHMR6OOPfE8oVVpdWIWANOIVPT75n1FhPknmRVloVmzyotH5G0JD.,$2a$10$AbbSKDa9HFL5LHg1PRif.ukfiC90Ybp4dBrLL82xKj3Qc19N4S7I2,$2a$10$4KJULL05MP3ZPihFp3Myu.kDQORG7qFdv2MHJnef7FUfidChXNUjm,"+
                "$2a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Nun1JG8P/re3wglgvcIG.MuG,$2a$10$0mud1YlzY.l5rxHkV16Veu3Qtw3Dbfc9MC9AqSSyS5c7X5orTGGdC,$2a$10$E2NhAxELYXJZQvwtEjhh5Of/tLKlhy7NCAtjacxQXfE1totdK2TUm,$2a$10$CghuySHeWIzrmzsYq2Q.HeLItIK5SeAoaLTC6sThidNtAk50BVbCC,$2a$10$gAa8lhKJpiK5KFMWgH7VCuioNsys/8EEsFOOzw.0G.O1jEbsoNyCC,"+
                "$2a$10$LpBends9aroD4uZOR0UB9.u7HROrFRtHOj5DbnCiUD3bT49HJTovK,$2a$10$SePADrelDadID7JmXqyfC.a0oaj0cScph6oXXamodOZdr//dnZSje,$2a$10$ghijJFE5V7uGzoQ6Yrq0Ce6CC.Yj8v.onKr9yuxdHYZcGx2rXzWTK,$2a$10$9NV3bUgsS4c.RHcwnF6OVOd7w1u.sa0X4vQkDq1J9.pPT5o8AWbx6,$2a$10$vH5cEESBaZWgOBf3GQsMHuW8LbtFH.7hvYNYYWsAOBad353uz8FhG,$2a$10$L7T0X60X.Bme0HOx.xR4s.BfRCzMEBinj2lfL8UXgZWNvDM2TnUh6,$2a$10$PkxOj4JHd53OCttbQPZofuLfRkyWno7hGQfKw1.hBy3jD0gUisJgm,$2a$10$B8.QnBNqITn1uT4nydWuneM9X.mqKYCPSxohR/7SF.S1X3b/XWYLa,"+
                "$2a$10$nnK/wOCVzZTwU2ZrYVoNdOuhyWm/vDiqNJn.vTkVEFu137HOQagu.,$2a$10$wuFgwwNS9DDnj1vi.iq94up3KStQFUs7pN2gO/ndI6ERMbdeAa2sm,$2a$10$I6HqOxQe7YCZ5Icmva3jw.h3KGw9B6N9Uo6Tcg0r62bHKg6xWYKO6,$2a$10$yRn6PaFnHoujIgXqfEJcHepvXvEN0m5Qa.19RNV28H7IwzOt4Hhxu,$2a$10$ucs4zz9jCSzyDEA0LJqrX.RosuU1sPuSvBiM1IPL1nsX5V59it0Au,$2a$10$7YFVsVTqykrSXVu3bPl1S.uoj2onQwi21eVt6mZY3Y/dVpxTEgoLW,$2a$10$hNcAC5qMNTTxz.vH1nZLP.T4S9sPNTuG0KgDX1hylcMrMpaEfwRZ2,$2a$10$kupfow5/FMa7LNSaLoKM5.d5zU0icKtKSH8WHx30irK3G.C3pLyee,"+
                "$2a$10$N6xPqq44DmnBlWbJgiMNye/Fzm3.yxYwXIDBeALhBZNN1.xonwMdG,$2a$10$pYPzdyOaDBlOUd1PcGZDJeK5dtE35j4qNgJVHdCYPpxctmZ56Jrum,$2a$10$jRU.o6rq0fe3mPqO/YDZiu/rWyZop4UPYjUf27EbEfTxX56e2eM82,$2a$10$.tZ6GCOI/EG1x5Z7scAauOgNkFduxJf94oVB0tyEGllcRXje6UX9u,$2a$10$uIg7q24d34w4qa81YnQjwuYVK25EJxgw6DPn0KiLVQQ04CNfqd.0u,$2a$10$Hl67tZsGzurSuq1aXOmTguu6QF46GURJuyJxGIHTRATxSMsNFtJ2W,$2a$10$Qo0gRZUYigjxwJ5KmhkRIOjBkttk3GM06drYv96ERpk53F9039FgC,$2a$10$a/g0xm854nvQAuh4Ko0PYuVo70zIGSuD1g5MVkMD2ciVXKDntwtj2,"+
                "$2a$10$RT5td108sIGzIY23M4X1weksRvuydT34d3N7duu1Cd6OZMh2agOt2,$2a$10$.qd.8zD81cBQOrnzhSgWUuLYAuft2M86hfsD6siHvVTCyL0MZwfQG,$2a$10$eYDWFSzBwhQssYhpJh1UK.XMndeQtW2uTbAb3TTU5SK8q0eCHiqYG,$2a$10$6PueANimU3hlXN8j3IKX..1zWPRVnI9y1sdR1d9C/cVYYK55.ZEgC,$2a$10$j7xKdgRPgu4XtFnfjDAkdObkEuSByemURcPOpz3NuG/W5oPVLQcOC,$2a$10$ZLVe.LAKVMW66f7rvYpcNu8BlJj6cxs2zST.bLFTIHCjz6GKhA7L.,$2a$10$aJYhOZNu.bZKu6wyHy5u6uUowAr2sY4NcSn/IpQexn9nemlVZBdfa,$2a$10$Q66gF1W1WYQuigYOaXtWT.Npoz4.0Zl.OJacjvE5bVrlbbKVJQjuW,$2a$10$mV4b7hq3gpJq7cwaiLUJ8OBnu1bOopWyeTuk8aCID6WzlaM3TuoEy,$2a$10$rkSIXEFmcmSOHs0eIc16Ous0gC83P3uIg9EV1vqkw3G9YysKKRof6,"+
                "$2a$10$LxyHFhCGKN85FYn4I3s/yeVxaEV4Q4zutHpQMiaYFTO/m.neAJ2eK,$2a$10$RmdiQrErmW4T1H91bARr3eOb/5EeJdGElP1VPKbplOKBi8VK1PZ1O,$2a$10$6Sc/VvEvcxhAIgH7kUY60.QlM4xU2eHKFxdxXBsQmMZzis4GY2buS,$2a$10$G9FBv5rBu/stjHXImxETgukeTIK2DC65x9m3Ogd91UR8/7L/WhX9W");
        String[] split = str.split(",");
        //私钥
        String privateKey = privateKeyStr;
        for (String s : split) {
            //解密字符串
            String decryptText = SM2Encryptor.decryptText(privateKey, s);
            System.out.println("解密后密码:"+decryptText);
        }

    }

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

    /**
     * RSA密钥对对象
     */
    public static class SmKeyPair {
        private String publicKey;
        private String privateKey;

        public SmKeyPair() {

        }

        public SmKeyPair(String publicKey, String privateKey) {
            this.publicKey = publicKey;
            this.privateKey = privateKey;
        }

        public String getPublicKey() {
            return publicKey;
        }

        public void setPublicKey(String publicKey) {
            this.publicKey = publicKey;
        }

        public String getPrivateKey() {
            return privateKey;
        }

        public void setPrivateKey(String privateKey) {
            this.privateKey = privateKey;
        }
    }

}



然后运行里面的main方法获取公钥和私钥,保存起来
在这里插入图片描述
在这里插入图片描述
然后再application.yml文件中加入一个配置:
在这里插入图片描述

#SM2解密私钥
SM_privateKey: 92b704fee9ac448ac27abfa537021ab42d0035151f01fdc03e49b0c2f5496148

最后在登录接口那里调用解密方法


    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) throws Exception
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), SM2Encryptor.decryptText(SM_privateKey, loginBody.getPassword()), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

在这里插入图片描述
到此后端的工作就做完了

前端

前段需要先

npm i sm-crypto

在需要生成的模块,如common模块下新建一个工具类
前端代码:
在utils下新建smcrypto.js,把公钥和私钥放进来

import { sm2 } from 'sm-crypto'

const publicKey = "04b9fd451e0d0d5517069076edbc7dc83b3a885307bc8cf00185769f6818bcdf958f8dc4c8575f33dcfbe0bb18c4f651892a05a4fd923f01db2e3ad09fc4bf2878"
const privateKey = '92b704fee9ac448ac27abfa537021ab42d0035151f01fdc03e49b0c2f5496148'
const cipherMode=1

// sm2公钥加密
export function smEncryptor(password) {
  password = sm2.doEncrypt(password, publicKey, cipherMode)
  return password
}

// sm私钥解密
export function decrypt(txt) {
  return sm2.doDecrypt(txt, privateKey, cipherMode)
}

然后在登录的地方进行加密:

      const password = smEncryptor(userInfo.password)

在这里插入图片描述
最后就是测试效果
在这里插入图片描述

文章来源:https://blog.csdn.net/ksjdbdh/article/details/135569177
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。