SpringBoot业务开发 07、Springboot集成非对称加解密

举报
长路 发表于 2022/11/28 19:52:33 2022/11/28
【摘要】 文章目录前言资源初始配置一、vue项目使用二、Springboot集成完整方法工具类快速使用参考文章 前言 本篇博客是SpringBoot来集成非对称加密解密,若文章中出现相关问题,请指出! 所有博客文件目录索引:博客目录索引(持续更新) 资源 RSA,RSA2公钥私钥加密解密 支付宝在线加密:强烈推荐不报错! 初始配置 1、阿里文档 下载工具包: 2、进行安装后点击生成秘钥即可 一、vue

@[toc]

前言

本篇博客是SpringBoot来集成非对称加密解密,若文章中出现相关问题,请指出!

所有博客文件目录索引:博客目录索引(持续更新)

资源

RSA,RSA2公钥私钥加密解密

支付宝在线加密:强烈推荐不报错!

初始配置

1、阿里文档

下载工具包:

image-20220412155228023

2、进行安装后点击生成秘钥即可

image-20220412155339532


一、vue项目使用

引入

npm install jsencrypt

image-20211129191507985

import JSEncrypt from 'jsencrypt/bin/jsencrypt.min'

// 密钥对生成 http://web.chacuo.net/netrsakeypair

const publicKey = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKoR8mX0rGKLqzcWmOzbfj64K8ZIgOdH\n' +
  'nzkXSOVOZbFu/TJhZ7rFAN+eaGkl3C4buccQd/EjEsj9ir7ijT7h96MCAwEAAQ=='

const privateKey = 'MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAqhHyZfSsYourNxaY\n' +
  '7Nt+PrgrxkiA50efORdI5U5lsW79MmFnusUA355oaSXcLhu5xxB38SMSyP2KvuKN\n' +
  'PuH3owIDAQABAkAfoiLyL+Z4lf4Myxk6xUDgLaWGximj20CUf+5BKKnlrK+Ed8gA\n' +
  'kM0HqoTt2UZwA5E2MzS4EI2gjfQhz5X28uqxAiEA3wNFxfrCZlSZHb0gn2zDpWow\n' +
  'cSxQAgiCstxGUoOqlW8CIQDDOerGKH5OmCJ4Z21v+F25WaHYPxCFMvwxpcw99Ecv\n' +
  'DQIgIdhDTIqD2jfYjPTY8Jj3EDGPbH2HHuffvflECt3Ek60CIQCFRlCkHpi7hthh\n' +
  'YhovyloRYsM+IS9h/0BzlEAuO0ktMQIgSPT3aFAgJYwKpqRYKlLDVcflZFCKY7u3\n' +
  'UP8iWi1Qw0Y='

// 加密
export function encrypt(txt) {
  const encryptor = new JSEncrypt()
  encryptor.setPublicKey(publicKey) // 设置公钥
  return encryptor.encrypt(txt) // 对数据进行加密
}

// 解密
export function decrypt(txt) {
  const encryptor = new JSEncrypt()
  encryptor.setPrivateKey(privateKey) // 设置私钥
  return encryptor.decrypt(txt) // 对数据进行解密
}

使用

import { encrypt, decrypt } from '@/utils/jsencrypt.js'

test () {
    console.log('密码:123456')
    const num = encrypt('123456')
    console.log('加密后:' + num)
    console.log('解密后:' + decrypt(num))
},

二、Springboot集成

完整方法工具类

测试:

public static void main(String[] args) throws Exception {
    String jiami = "bZEWt/ZCs6A7WoeopCnUs7t/SEoxvF+UH4UZhZm8BzjAjZ2HFHThfu/H9G9BdktIowHXo8mQqS1n08kslgqY7aKwxyg88xZXsJ9BOY5MUAnkbQAG3luejMp4B3Eoz+nL8hMrmrh4yUyRFRIsz7/EGuIkeKLzhq9bwOQ2aZ4LgMh7/hETbQuDtF10aKMcPbwrB/8NCSaoGsQGXEUtUjJxARFXGnrtH2dP4GDfth9rtyJMfpRqXTFyhQMpXrubcI7FmyZonoHQlCPJ+2z2E8XzaQOo3H5YLBb/CVvr2JEFbCuWkvyB+dNVvRS/dYiacrd26UAO9VhzdiOuNc3ePJT4TA==";
    System.out.println(decryptByPrivateKey(jiami));
}

完整工具类:

package com.zhifeng.common.Utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @ClassName RsaUtils
 * @Author ChangLu
 * @Date 2021/11/29 20:05
 * @Description TODO
 */
public class RsaUtils {

    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iYA6Fe2fQ8baKGUVFoNNHJgHx6KmrxoXsPeMJgyO0Q+sCP0ZrPXbZLwQCm9itMFkpQ8xnwL+BSGNNr+Wrj2tK+TA+N4LFxd3u6iAQKBgQDIsHpNoXJheizOpQdcL619LT/MCXhD/rklLZzl4oV5qb/CfVEg3LqUF/h7c9RlsMvT+TpfSA+VEAoz+k8Igf45GAYkIIiDWAVfckMEnJISJfKVIN+ZYCUA8lhNa7SIgaxZnCbOczeEuOrfh0SWFxMsIdmFA7JUZm3nVebik/2dwQKBgQDESaeaGQCZuy5PVLbSAm1dAkrEOdnF4qQ5VbdcJLvKhQ98a5hFi9HmiFRrJIoUG2ePdiSr50RCZ7rgPhbvY+mkoXLalqsWmgIkitnggX0A/TJ2IDN4QZKuVWpJ2upBNCTCbuQiqg15etMXbAYEWKYHR2EjEl23HQm5lG7P1T8ciQKBgDraXhNz/AoP/SHgjYcASF1ELshUIpu2EG+Rr8hOpJvoJt8PRwJfGKwjV3BEqI3lyfBwzyhwBnnNSWCy0AiLrpTpsatYixAReQnjhTnN/Jwr2rbW/BuLcW6Uo0aZBkld1cA1pb+3VBms7Nv+XCOzwqCXkKWMTvinTSWhMGNTyPVBAoGAGAR3KIjUpPrdUMGp2QqI/S9xnI8DkY4I0Ccn13N7Mu2TFoNHz4KrPU0DH1UKPCmaQ1iOZiZXGNT+bb/LKKGODiHfHtX+uzY++t+uhyTw+bUBfqi0A4vqecBj0AOkVDQgJ1ZQPdmW6n1X5O7H0bJTJmLahOMTant4HCgIYw/RuBkCgYEAnWugBURLRAC3b7Sl4J3cAF7roJraWuqmi2iw9glf72BCuN19uvo7hBi8B1L8kKwcvpUIqISSLZfm6HQziRgxqwrDYdjUPJY/Y6ugEC0lRgOoAs22xOmW+AfQwGdXYKJf3Tp+hb9QmTDhngjyq9eU3SeL4kd11rC2veb8XyBUj6s=";


    /**
     * RSA密钥对对象
     */
    public static class RSAKeyPair {

        private String publicKey;
        private String privateKey;

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

        public String getPublicKey() {
            return publicKey;
        }

        public String getPrivateKey() {
            return privateKey;
        }

    }


    /**
     * 构建RSA密钥对
     *
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static RSAKeyPair generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
        String publicKeyString = Base64.encodeBase64String(rsaPublicKey.getEncoded());
        String privateKeyString = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
        RSAKeyPair rsaKeyPair = new RSAKeyPair(publicKeyString, privateKeyString);
        return rsaKeyPair;
    }

    /**
     * 公钥加密
     *
     * @param publicKeyText
     * @param text
     * @return
     */
    public static String encryptByPublicKey(String publicKeyText, String text) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] result = cipher.doFinal(text.getBytes());
        return Base64.encodeBase64String(result);
    }

    /**
     * 私钥解密
     *
     * @param privateKeyText
     * @param text
     * @return
     * @throws Exception
     */
    public static String decryptByPrivateKey(String text) throws Exception {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(Base64.decodeBase64(text));
        return new String(result);
    }

    /**
     * 公钥解密
     *
     * @param publicKeyText
     * @param text
     * @return
     * @throws Exception
     */
    public static String decryptByPublicKey(String publicKeyText, String text) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        byte[] result = cipher.doFinal(Base64.decodeBase64(text));
        return new String(result);
    }

    /**
     * 私钥加密
     *
     * @param privateKeyText
     * @param text
     * @return
     * @throws Exception
     */
    public static String encryptByPrivateKey(String privateKeyText, String text) throws Exception {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyText));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(text.getBytes());
        return Base64.encodeBase64String(result);
    }

//    /**
//     * 公钥加密私钥解密
//     */
//    private static void test1(RSAKeyPair keyPair, String source) throws Exception {
//        System.out.println("***************** 公钥加密私钥解密开始 *****************");
//        String text1 = encryptByPublicKey(keyPair.getPublicKey(), source);
//        String text2 = decryptByPrivateKey(keyPair.getPrivateKey(), text1);
//        System.out.println("加密前:" + source);
//        System.out.println("加密后:" + text1);
//        System.out.println("解密后:" + text2);
//        if (source.equals(text2)) {
//            System.out.println("解密字符串和原始字符串一致,解密成功");
//        } else {
//            System.out.println("解密字符串和原始字符串不一致,解密失败");
//        }
//        System.out.println("***************** 公钥加密私钥解密结束 *****************");
//    }
//
//    /**
//     * 私钥加密公钥解密
//     *
//     * @throws Exception
//     */
//    private static void test2(RSAKeyPair keyPair, String source) throws Exception {
//        System.out.println("***************** 私钥加密公钥解密开始 *****************");
//        String text1 = encryptByPrivateKey(keyPair.getPrivateKey(), source);
//        String text2 = decryptByPublicKey(keyPair.getPublicKey(), text1);
//        System.out.println("加密前:" + source);
//        System.out.println("加密后:" + text1);
//        System.out.println("解密后:" + text2);
//        if (source.equals(text2)) {
//            System.out.println("解密字符串和原始字符串一致,解密成功");
//        } else {
//            System.out.println("解密字符串和原始字符串不一致,解密失败");
//        }
//        System.out.println("***************** 私钥加密公钥解密结束 *****************");
//    }

}

快速使用

实际使用:

//2、非对称解密密码
try {
    loginBody.setPassword(RsaUtil.decryptByPrivateKey(loginBody.getPassword()));
} catch (Exception e) {
    throw new ServiceException("请不要尝试篡改密码!");
}

测试:

public static void main(String[] args) throws Exception{
    String password = "changlu";
    //使用公钥加密
    String encryptPassword = encryptByPublicKey(RsaUtil.publicKey, password);
    //传入加密过后的密码进行解密
    String decodePassword = decryptByPrivateKey(encryptPassword);
    System.out.println(decodePassword);
}

工具类:

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @ClassName RsaUtil
 * @Author ChangLu
 * @Date 4/12/2022 4:00 PM
 * @Description 非对称加解密工具类
 */
public class RsaUtil {

    private static String publicKey = "xxx";

    private static String privateKey = "xxx";

    /**
     * RSA密钥对对象
     */
    public static class RSAKeyPair {

        private String publicKey;
        private String privateKey;

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

        public String getPublicKey() {
            return publicKey;
        }

        public String getPrivateKey() {
            return privateKey;
        }

    }

    /**
     * 私钥解密
     *
     * @param privateKeyText
     * @param text
     * @return
     * @throws Exception
     */
    public static String decryptByPrivateKey(String text) throws Exception {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(Base64.decodeBase64(text));
        return new String(result);
    }

    /**
     * 公钥加密
     *
     * @param publicKeyText
     * @param text
     * @return
     */
    public static String encryptByPublicKey(String publicKeyText, String text) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] result = cipher.doFinal(text.getBytes());
        return Base64.encodeBase64String(result);
    }

}

参考文章

[1]. 在Vue项目中使用jsencrypt.js对数据进行加密传输

[2]. 利用jsencrypt.js 进行前端RSA加密,java后端解密

数据进行加密传输](https://blog.csdn.net/qq_37816525/article/details/101905567?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2~default~CTRLIST~default-1.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~CTRLIST~default-1.no_search_link)

[2]. 利用jsencrypt.js 进行前端RSA加密,java后端解密

[3]. JsEncrypt.js前端加密,java后端解密:超详细两种加密方式

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。