【springboot学习】使用jasypt明文加密

一般我们都会把数据库用户名,密码,redis用户名,密码等敏感信息写在property文件中,但是明文配置很不安全,那么我们就需要对明文进行加密,我们可以使用jasypt对敏感信息加密。

第一步,导入依赖的包

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

那这个包肯定支持加密解密,先看一下直接使用该类库如何加密解密:

import org.jasypt.util.text.BasicTextEncryptor;

public class JasyptTest {
	private static BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
	private static String salt = "welcome";// 加密的密钥

	static {
		textEncryptor.setPassword(salt);
	}

	public static String encrypt(final String password) {

		return textEncryptor.encrypt(password);// 需要加密的密码
	}

	public static String decrypt(final String password) {

		return textEncryptor.decrypt(password);
	}

	public static void main(final String[] args) {

		String password = "123456";
		String encrypt = encrypt(password);
		System.out.println(encrypt);
		System.out.println(decrypt(encrypt));

	}
}

这样我们就可以把要加密的密文放到property文件中

server.port=8081
server.context-path=/app

spring.redis.host=localhost
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=ENC(Hwpma7vHGZDeZlvWB00qSg==)

那接下来我们在程序中如何解密该密码然后连接到redis呢?

我们只需要在配置文件property中把密钥配置进去,jasypt就会根据密钥自动解密。具体原理可以看这篇文章

server.port=8081
server.context-path=/app
#jasypt加密密钥
jasypt.encryptor.password=welcome

spring.redis.host=localhost
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=ENC(Hwpma7vHGZDeZlvWB00qSg==)

但是密钥和密文都放在一起,这不是掩耳盗铃吗?我们可以用之前介绍的 外部文件配置

我们可以在启动项目时候使用命令行参数配置jasypt密钥 --jasypt.encryptor.password=welcome

或者使用环境变量来配置密钥。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值