jasypt加密数据库用户名密码

生产环境数据库密码上传到github上不安全,故考虑加密方式处理,本文基于最新的3.0.3版本介绍

1.引入maven依赖

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

<plugin>
	<groupId>com.github.ulisesbocchio</groupId>
	<artifactId>jasypt-maven-plugin</artifactId>
</plugin>

2.配置application.yml

jasypt:
  encryptor:
    password: shenjian #盐值

3.采用插件命令获得加密值

mvn jasypt:encrypt-value -Djasypt.encryptor.password="shenjian" -Djasypt.plugin.value="root"

加密后结果,从下图可以看出3.0.3默认使用PBEWITHHMACSHA512ANDAES_256加密算法

对当前结果解密

mvn jasypt:decrypt-value -Djasypt.encryptor.password="shenjian" -Djasypt.plugin.value="CbKzV4JPAIGLmGjNyNRgVJ8t6JN7xRW2lPh24VigJryoli/wAlNwbabHR8gIt0bM"

解密后结果

既然能够解密,呢么盐值的存取是比较重要的,稍后讲解

4.配置加密后的数据库

spring:
  # Mysql数据源
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/photo?serverTimezone=Asia/Shanghai&characterEncoding=utf8
    username: ENC(CbKzV4JPAIGLmGjNyNRgVJ8t6JN7xRW2lPh24VigJryoli/wAlNwbabHR8gIt0bM)
    password: ENC(R5BPqaEh0oa+fgAqthW0eFTMuooFHEjOglQ8o38gvEFTiCtORllppbF+932zh5Zc)
    driver-class-name: com.mysql.cj.jdbc.Driver

因为项目基于springboot,只要在启动类有@SpringBootApplication注解就可以了

5.启动参数中添加盐值

刚才看到可以解密加密后的值,呢么在配置文件中就不能存在盐值配置,删除application.yml中的盐值配置,可以采用启动参数配置或者从环境变量中获取方式,如下

方式1: 在idea启动时添加参数

--jasypt.encryptor.password=shenjian

方式2: springboot启动时添加参数

java -jar photo-api-0.0.1-SNAPSHOT.jar --jasypt.encryptor.password=shenjian

方式3:从linux环境变量中获取盐值

# 进入环境变量设置文件
vim /etc/profile 
# 在最后一行添加变量
export JASYPT_PASSWORD=shenjian
# 启动项目
java -jar photo-api-0.0.1-SNAPSHOT.jar --jasypt.encryptor.password=${JASYPT_PASSWORD}

6.常见问题

1)Caused by: java.lang.SecurityException: Cannot locate policy or framework files!

分析:由于3.0.3中使用的算法可能在java8的安全策略中没有,需要手动下载jce_policy-8并将里面的jar包放在如${JAVA_HOME}/jre/lib/security中,如下图所示:


欢迎关注公众号算法小生

猜你喜欢

转载自blog.csdn.net/SJshenjian/article/details/130302988