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

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
云数据库 RDS PostgreSQL,高可用系列 2核4GB
简介: 前言:在实际开发中,一些关键的信息肯定是要加密的,否则就太不安全了。比如连接数据库的用户名和密码,一般就需要加密。接下来就看看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
AI 代码解读

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

<context:property-placeholder location="classpath:jdbc.properties" />
AI 代码解读

要加密需要进行以下操作:
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="));
    }
}
AI 代码解读

这个类就实现了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=
AI 代码解读

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;
    }

}
AI 代码解读

这段代码就对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>
AI 代码解读

这里就把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);
    }

}
AI 代码解读

运行结果:


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>
AI 代码解读

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

#配置数据源加密的密钥
jasypt.encryptor.password=hellospringboot
AI 代码解读

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);
    }
}
AI 代码解读

运行结果:

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==)
AI 代码解读

注意:
加密字段需要用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);
    }
    
}
AI 代码解读
img_9c3a58770cbe04ba8420f4f386ac6c5a.png
image.png

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

总结:

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

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

目录
打赏
0
0
1
0
1
分享
相关文章
数据库数据恢复——sql server数据库被加密的数据恢复案例
SQL server数据库数据故障: SQL server数据库被加密,无法使用。 数据库MDF、LDF、log日志文件名字被篡改。 数据库备份被加密,文件名字被篡改。
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——少量配置信息的情形
本课主要讲解Spring Boot项目中的属性配置方法。在实际开发中,测试与生产环境的配置往往不同,因此不应将配置信息硬编码在代码中,而应使用配置文件管理,如`application.yml`。例如,在微服务架构下,可通过配置文件设置调用其他服务的地址(如订单服务端口8002),并利用`@Value`注解在代码中读取这些配置值。这种方式使项目更灵活,便于后续修改和维护。
70 0
Spring Boot yml 配置敏感信息加密
本文介绍了如何在 Spring Boot 项目中使用 Jasypt 实现配置文件加密,包含添加依赖、配置密钥、生成加密值、在配置中使用加密值及验证步骤,并提供了注意事项,确保敏感信息的安全管理。
129 1
Jasypt加密数据库配置信息
本文介绍了使用 Jasypt 对配置文件中的公网数据库认证信息进行加密的方法,以提升系统安全性。主要内容包括:1. 背景介绍;2. 前期准备,如依赖导入及版本选择;3. 生成密钥并实现加解密测试;4. 在配置文件中应用加密后的密码,并通过测试接口验证解密结果。确保密码安全的同时,保障系统的正常运行。
148 3
Jasypt加密数据库配置信息
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——指定项目配置文件
在实际项目中,开发环境和生产环境的配置往往不同。为简化配置切换,可通过创建 `application-dev.yml` 和 `application-pro.yml` 分别管理开发与生产环境配置,如设置不同端口(8001/8002)。在 `application.yml` 中使用 `spring.profiles.active` 指定加载的配置文件,实现环境快速切换。本节还介绍了通过配置类读取参数的方法,适用于微服务场景,提升代码可维护性。课程源码可从 [Gitee](https://gitee.com/eson15/springboot_study) 下载。
116 0
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——少量配置信息的情形
在微服务架构中,随着业务复杂度增加,项目可能需要调用多个微服务。为避免使用`@Value`注解逐一引入配置的繁琐,可通过定义配置类(如`MicroServiceUrl`)并结合`@ConfigurationProperties`注解实现批量管理。此方法需在配置文件中设置微服务地址(如订单、用户、购物车服务),并通过`@Component`将配置类纳入Spring容器。最后,在Controller中通过`@Resource`注入配置类即可便捷使用,提升代码可维护性。
69 0
如何在Spring Boot中实现数据加密
本文介绍了如何在Spring Boot中实现数据加密。首先阐述了数据加密的重要性与应用场景,接着讲解了对称加密和非对称加密的原理及区别。通过添加依赖、配置加密算法、编写加密工具类等步骤,展示了具体实现方法,并在业务代码中应用加密技术保护敏感数据。希望对开发者有所帮助。
201 7
|
5月前
|
java语言后台管理ruoyi后台管理框架-登录提示“无效的会话,或者会话已过期,请重新登录。”-扩展知识数据库中密码加密的方法-问题如何解决-以及如何重置若依后台管理框架admin密码-优雅草卓伊凡
java语言后台管理ruoyi后台管理框架-登录提示“无效的会话,或者会话已过期,请重新登录。”-扩展知识数据库中密码加密的方法-问题如何解决-以及如何重置若依后台管理框架admin密码-优雅草卓伊凡
460 3
java语言后台管理ruoyi后台管理框架-登录提示“无效的会话,或者会话已过期,请重新登录。”-扩展知识数据库中密码加密的方法-问题如何解决-以及如何重置若依后台管理框架admin密码-优雅草卓伊凡
Spring Boot 两种部署到服务器的方式
本文介绍了Spring Boot项目的两种部署方式:jar包和war包。Jar包方式使用内置Tomcat,只需配置JDK 1.8及以上环境,通过`nohup java -jar`命令后台运行,并开放服务器端口即可访问。War包则需将项目打包后放入外部Tomcat的webapps目录,修改启动类继承`SpringBootServletInitializer`并调整pom.xml中的打包类型为war,最后启动Tomcat访问应用。两者各有优劣,jar包更简单便捷,而war包适合传统部署场景。需要注意的是,war包部署时,内置Tomcat的端口配置不会生效。
1805 17
Spring Boot 两种部署到服务器的方式
GBase 数据库 加密客户端---数据库用户口令非明文存放需求的实现
GBase 数据库 加密客户端---数据库用户口令非明文存放需求的实现

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问