项目配置中数据库密码的加密

        以SpringBoot项目为例,一般我们在开发的时候,需要在application.yml文件中写上数据库的连接信息,包括数据库密码。通常我们将数据库密码也是以明码的方式书写的,这就导致数据库密码裸露在外,不够安全。

        下面使用PBE加密算法:PBEWITHMD5andDES,对数据库密码进行加密,在配置文件中使用密文,让数据库密码不至于太过暴漏。

1、添加依赖

        <!-- 数据库加密配置-->
        <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

2、书写加密方法

import org.apache.ibatis.mapping.Environment;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig;

/**
 * 密码加密类
 * @author one_smile
 *
 */
public class JasyptUtil {
	
	//加密
	public void encrypt() {
		StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
		EnvironmentPBEConfig config = new EnvironmentPBEConfig();
		
		//加密的算法,这个算法是默认的
		config.setAlgorithm("PBEWithMD5AndDES");
		//加密的密钥,自定义
		config.setPassword("one_smile");
		standardPBEStringEncryptor.setConfig(config);
        //xxsxx是需要加密的明文
		String plainTextString = "xxsxx";
		String encryptedTextString = standardPBEStringEncryptor.encrypt(plainTextString);
        //encryptedTextString是加密后的密文 
		System.out.println(encryptedTextString);
	}
	
}

        加密方法可以通过main方法执行,直接生成最后的密文串即可

3、修改配置文件appllication.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/memo?useUnicode=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=utf-8
    username: root
    #需要注意加秘密串需要写在ENC()内
    password: ENC(zviS44Qa3TexXKCF/piDcE+LTYnUP3Wn)
    driver-class-name: com.mysql.cj.jdbc.Driver
jasypt:
  encryptor:
    #此处的one_smile需要和加密方法中的自定义密钥一致
    password: one_smile

附:

下面附上解密方法

package com.onesmile.memo.utils;

import org.apache.ibatis.mapping.Environment;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig;

/**
 * 密码加密类
 * @author one_smile
 *
 */
public class JasyptUtil {
	
	//解密
	public void decipherer() {
		StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
		EnvironmentPBEConfig config = new EnvironmentPBEConfig();
		
		//加解密算法
		config.setAlgorithm("PBEWithMD5AndDES");
        //此处解密密钥需要和加密密钥一致
		config.setPassword("one_smile");
		standardPBEStringEncryptor.setConfig(config);
        //内容为加密后的密码串
		String encryptedTextString = "ldAXhQ7gZCsR0kgKFSlO8d+ecn6AYXhK";
        //解密后结果
		String plainTextString = standardPBEStringEncryptor.decrypt(encryptedTextString);
		System.out.println(plainTextString);
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

one_smail

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值