spring和springboot中加密连接数据库的信息

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介: 前言:在实际开发中,一些关键的信息肯定是要加密的,否则就太不安全了。比如连接数据库的用户名和密码,一般就需要加密。接下来就看看spring项目和spring boot项目中分别是如何加密这些信息的。

前言:

在实际开发中,一些关键的信息肯定是要加密的,否则就太不安全了。比如连接数据库的用户名和密码,一般就需要加密。接下来就看看spring项目和spring boot项目中分别是如何加密这些信息的。

一、spring中加密连接数据库的信息:

spring项目中,我们一般把连接数据库的信息写在jdbc.properties中,然后在spring-dao.xml中读取配置信息。
未加密是这样写的:
jdbc.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///test?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123

然后在spring-dao.xml中读取:

<context:property-placeholder location="classpath:jdbc.properties" />

要加密需要进行以下操作:
1、编写DES算法加密工具类:
DESUtil.java:

import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


/**
 * 用DES对称算法加密数据库连接的信息</br>
 * 所谓对称算法就是加密和解密使用相同的key
 * 
 * @author zhu
 *
 */
public class DESUtil {
    private static Key key;
    // 设置密钥key
    private static String KEY_STR = "myKey";
    private static String CHARSETNAME = "UTF-8";
    private static String ALGORITHM = "DES";

    static {
        try {
            // 生成des算法对象
            KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
            // 运用SHA1安全策略
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            // 设置密钥种子
            secureRandom.setSeed(KEY_STR.getBytes());
            // 初始化基于SHA1的算法对象
            generator.init(secureRandom);
            // 生成密钥对象
            key = generator.generateKey();
            generator = null;
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    /**
     * 获取加密后的信息
     * 
     * @param str
     * @return
     */
    public static String getEncryptString(String str) {
        // 基于BASE64编码,接收byte[]并转换层String
        BASE64Encoder base64encoder = new BASE64Encoder();
        try {
            // utf-8编码
            byte[] bytes = str.getBytes(CHARSETNAME);
            // 获取加密对象
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            // 初始化密码信息
            cipher.init(Cipher.ENCRYPT_MODE, key);
            // 加密
            byte[] doFinal = cipher.doFinal(bytes);
            // 返回
            return base64encoder.encode(doFinal);
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    /**
     * 获取解密之后的信息
     * 
     * @param str
     * @return
     */
    public static String getDecryptString(String str) {
        //基于BASE64编码,接收byte[]并转换成String
        BASE64Decoder base64decoder = new BASE64Decoder();
        try {
            //将字符串decode成byte[]
            byte[] bytes = base64decoder.decodeBuffer(str);
            //获取解密对象
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            //初始化解密信息
            cipher.init(Cipher.DECRYPT_MODE, key);
            //解密
            byte[] doFinal = cipher.doFinal(bytes);
            //返回解密之后的信息
            return new String(doFinal,CHARSETNAME);
        }catch(Exception e) {
            throw new RuntimeException(e);
        }
    }
    
       /**
     * 测试
     * 
     * @param args
     */
    public static void main(String[] args) {
        // 加密root字符串
        System.out.println(getEncryptString("root"));
        // 加密123
        System.out.println(getEncryptString("123"));
        // 解密WnplV/ietfQ=
        System.out.println(getDecryptString("WnplV/ietfQ="));
    }
}

这个类就实现了DES算法加密字符串,把需要加密的字段传入getEncryptString方法即可加密。看运行效果:

img_5b7250b42b551fd95dd3022aa4dc6370.png
image.png

注意:
在编写这个类的时候,BASE64Encoder一直报错,找不到 sun.misc.BASE64Encoder包,没办法import这个包。
解决办法:
选中项目 ---> build path ---> libraries ---> jre system library ---> access rules
---> edit ---> add ---> accessble ---> ** ---> ok
img_323747561eb4f3cfb4b543d48d70a6f5.png
image.png

img_55633908a9627e932b50646b0c9cadf9.png
image.png

2、把jdbc.properties中的字段换成加密后的
jdbc.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///test?useUnicode=true&characterEncoding=utf8
jdbc.username=WnplV/ietfQ=
jdbc.password=um461kxL7IU=

3、在spring读取配置时解密
以上两步完成了加密,但是这样spring读取时并不会自动解密这些经过加密的字段,所以还需要进行如下操作:
EncryptPropertyPlaceholderConfigurer.java:

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

/**
 * 在spring-dao加载jdbc.properties时,将加密信息解密出来
 * 
 * @author zhu
 *
 */
public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
    // 需要加密的字段数组
    private String[] encryptPropNames = { "jdbc.username", "jdbc.password" };

    protected String convertProperty(String propertyName, String propertyValue) {
        if (isEncryptProp(propertyName)) {
            // 对加密的字段进行解密工作(调用DESUtil中的解密方法)
            String decryptValue = DESUtil.getDecryptString(propertyValue);
            return decryptValue;
        } else {
            return propertyValue;
        }
    }

    /**
     * 该属性是否已加密
     * 
     * @param propertyName
     * @return
     */
    private boolean isEncryptProp(String propertyName) {
        // 若等于需要加密的field,则进行加密
        for (String encryptpropertyName : encryptPropNames) {
            if (encryptpropertyName.equals(propertyName)) {
                return true;
            }
        }
        return false;
    }

}

这段代码就对jdbc.username和jdbc.password进行了解密。然后在spring-dao.xml中以如下方式读取jdbc.properties:
spring-dao.xml:

    <bean
        class="com.zhu.util.EncryptPropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
        <property name="fileEncoding" value="UTF-8" />
    </bean>

这里就把EncryptPropertyPlaceholderConfigurer配置成了bean,用这个类去读取jdbc.properties就可以解密了。

4、连接测试:
DESTest.java:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.mysql.jdbc.Driver;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:spring/spring-dao.xml"})
public class DESTest {
    
    @Test
    public void testGetDataSource() {
        System.out.println(Driver.class);
    }

}

运行结果:


img_a61a1a8a5e4dacc1080b76efbcd3dd02.png
image.png

连接成功!

二、springboot项目中加密数据库连接信息:

springboot项目没有jdbc.properties,也没有spring-dao.xml,全都写在application.properties或application.yml中。需要加密的话执行如下操作即可:

1、引入jasypt的jar包:

        <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>1.16</version>
        </dependency>

2、在application.properties中配置加密key:
这个key可以自己随便写,我写的是hellospringboot。

#配置数据源加密的密钥
jasypt.encryptor.password=hellospringboot

3、使用jasypt加密字段:

import org.jasypt.encryption.StringEncryptor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class test {
    
    //注入StringEncryptor
    @Autowired
    StringEncryptor encryptor;
    
    @Test
    public void encry() {
        //加密root
        String username = encryptor.encrypt("root");
        System.out.println(username);
        //加密123
        String password = encryptor.encrypt("123");
        System.out.println(password);
    }
}

运行结果:

img_9267e8efb5917301573819ad214ea207.png
image.png

这两个就是root和123加密后的结果。
注意:
这个测试类每运行一次输出的结果都是不一样的,比如第一次运行是上图结果,第二次运行加密结果又不一样了,这是正常现象。随便复制哪一次的运行结果到application.properties中都行。

4、在application.properties中配置连接数据库的信息:

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql:///meilianMall?useUnicode=true&characterEncoding=utf8
spring.datasource.username=ENC(UltArcVy251RWehUvajQmg==)
spring.datasource.password=ENC(y23g0pb97XsBULm3ILNWTg==)

注意:
加密字段需要用ENC(密文)的形式,直接写spring.datasource.username=UltArcVy251RWehUvajQmg是无效的。

5、连接测试:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.mysql.jdbc.Driver;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class test {

    @Test
    public void testGetDataSource() {
        System.out.println(Driver.class);
    }
    
}
img_9c3a58770cbe04ba8420f4f386ac6c5a.png
image.png

可以看到也是连接成功的。

总结:

spring项目中加密数据库连接信息的方法稍微麻烦一点,要加密又要解密,而springboot采用的jasypt加密相当于解密工作它会自动完成,我们只需要在application.properties中配置密钥和加密后的信息即可。

以上内容属于个人笔记整理,如有错误,欢迎批评指正!

相关文章
|
29天前
|
SQL 监控 Java
在IDEA 、springboot中使用切面aop实现日志信息的记录到数据库
这篇文章介绍了如何在IDEA和Spring Boot中使用AOP技术实现日志信息的记录到数据库的详细步骤和代码示例。
在IDEA 、springboot中使用切面aop实现日志信息的记录到数据库
|
18天前
|
缓存 NoSQL Java
【Azure Redis 缓存】示例使用 redisson-spring-boot-starter 连接/使用 Azure Redis 服务
【Azure Redis 缓存】示例使用 redisson-spring-boot-starter 连接/使用 Azure Redis 服务
|
28天前
|
SQL JavaScript 前端开发
vue中使用分页组件、将从数据库中查询出来的数据分页展示(前后端分离SpringBoot+Vue)
这篇文章详细介绍了如何在Vue.js中使用分页组件展示从数据库查询出来的数据,包括前端Vue页面的表格和分页组件代码,以及后端SpringBoot的控制层和SQL查询语句。
vue中使用分页组件、将从数据库中查询出来的数据分页展示(前后端分离SpringBoot+Vue)
|
11天前
|
安全 网络安全 数据安全/隐私保护
网络安全漏洞与加密技术:保护信息的艺术
【8月更文挑战第31天】在数字时代,网络安全和信息安全的重要性日益凸显。本文将探讨网络安全漏洞、加密技术以及提升安全意识等方面的内容。我们将通过实际代码示例和案例分析,深入了解网络攻击者如何利用安全漏洞进行攻击,以及如何运用加密技术来保护数据安全。同时,我们还将讨论如何提高个人和组织的安全意识,以应对不断变化的网络安全威胁。让我们一起探索这个充满挑战和机遇的领域吧!
|
20天前
|
安全 Java 关系型数据库
毕设项目&课程设计&毕设项目:基于springboot+jsp实现的健身房管理系统(含教程&源码&数据库数据)
本文介绍了一款基于Spring Boot和JSP技术实现的健身房管理系统。随着健康生活观念的普及,健身房成为日常锻炼的重要场所,高效管理会员信息、课程安排等变得尤为重要。该系统旨在通过简洁的操作界面帮助管理者轻松处理日常运营挑战。技术栈包括:JDK 1.8、Maven 3.6、MySQL 8.0、JSP、Shiro、Spring Boot 2.0等。系统功能覆盖登录、会员管理(如会员列表、充值管理)、教练管理、课程管理、器材管理、物品遗失管理、商品管理及信息统计等多方面。
|
18天前
|
JavaScript Java 关系型数据库
毕设项目&课程设计&毕设项目:基于springboot+vue实现的前后端分离的考试管理系统(含教程&源码&数据库数据)
在数字化时代背景下,本文详细介绍了如何使用Spring Boot框架结合Vue.js技术栈,实现一个前后端分离的考试管理系统。该系统旨在提升考试管理效率,优化用户体验,确保数据安全及可维护性。技术选型包括:Spring Boot 2.0、Vue.js 2.0、Node.js 12.14.0、MySQL 8.0、Element-UI等。系统功能涵盖登录注册、学员考试(包括查看试卷、答题、成绩查询等)、管理员功能(题库管理、试题管理、试卷管理、系统设置等)。
毕设项目&课程设计&毕设项目:基于springboot+vue实现的前后端分离的考试管理系统(含教程&源码&数据库数据)
|
23天前
|
JavaScript Java Maven
毕设项目&课程设计&毕设项目:springboot+vue实现的在线求职管理平台(含教程&源码&数据库数据)
本文介绍了一款基于Spring Boot和Vue.js实现的在线求职平台。该平台采用了前后端分离的架构,使用Spring Boot作为后端服务
毕设项目&课程设计&毕设项目:springboot+vue实现的在线求职管理平台(含教程&源码&数据库数据)
|
28天前
|
XML SQL JavaScript
在vue页面引入echarts,图表的数据来自数据库 springboot+mybatis+vue+elementui+echarts实现图表的制作
这篇文章介绍了如何在Vue页面中结合SpringBoot、MyBatis、ElementUI和ECharts,实现从数据库获取数据并展示为图表的过程,包括前端和后端的代码实现以及遇到的问题和解决方法。
在vue页面引入echarts,图表的数据来自数据库 springboot+mybatis+vue+elementui+echarts实现图表的制作
|
30天前
|
存储 SQL 安全
网络防线:揭秘网络安全漏洞与信息加密的奥秘
在数字时代,网络安全与信息保护如同一场没有硝烟的战争。本文将带您深入了解网络安全的薄弱环节,探索加密技术如何成为守护信息安全的利剑,并强调提升个人和组织安全意识的重要性。从常见漏洞到防护策略,再到加密技术的演变,我们将一步步揭开网络安全的神秘面纱,让您在这个充满未知的数字世界中更加从容不迫。
30 2
|
1月前
|
安全 Java Shell
"SpringBoot防窥秘籍大公开!ProGuard混淆+xjar加密,让你的代码穿上隐形斗篷,黑客也无奈!"
【8月更文挑战第11天】开发SpringBoot应用时,保护代码免遭反编译至关重要。本文介绍如何运用ProGuard和xjar强化安全性。ProGuard能混淆代码,去除未使用的部分,压缩字节码,使反编译困难。需配置ProGuard规则文件并处理jar包。xjar则进一步加密jar包内容,即使被解压也无法直接读取。结合使用这两种工具可显著提高代码安全性,有效保护商业机密及知识产权。
139 3