整合 jasypt 加密到 springboot 工程

it2024-04-11  50

前言:

springboot 工程涉及到一些重要的连接,涉密连接明文传参隐患很大,所以需要配置加密, jasypt 是目前最好用的加密工具。

1. 官网

https://github.com/ulisesbocchio/jasypt-spring-boot tips: 官网目前是 3.0.3,如果你是jdk 1.8 版本可能会有问题,这个后面再说。

2. maven 依赖

鉴于 3.0.3 版本有些问题,以下用旧版本 2.0.0

<dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency>
3. yml 文件配置
jasypt: encryptor: password: thisisapasswordsecret

tips: password 不建议在这里配置

如果你是 IDEA 启动,建议加上启动环境参数 jasypt.encryptor.password=thisisapasswordsecret如果启动 jar 包,启动参数加上 java -jar -Djasypt.encryptor.password=thisisapasswordsecret
4. 获取加密信息

jasypt 每个版本之间可能变动很大,一定要注意版本

官网默认方法如下:

/** * jasypt 2.0.0 版本默认加密方法 */ @Test void getPwdInfo() { PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); SimpleStringPBEConfig config = new SimpleStringPBEConfig(); config.setPassword("thisisapasswordsecret"); config.setAlgorithm("PBEWithMD5AndDES"); config.setKeyObtentionIterations("1000"); config.setPoolSize("1"); config.setProviderName(null); config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator"); config.setStringOutputType("base64"); encryptor.setConfig(config); System.out.println(encryptor.encrypt("you origin password")); }

打印加密后的结果:

k6TzikllCeo5j1zXszzbYq+fSBT3OfuwePbda1+jHBQ=
5. 使用

在 yml 配置文件中把需要加密的地方改成:

spring: datasource: url: jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver username: root password: ENC(Y2nHn53El0ronXEJmgvrjvVYPEOKbXVqgu+5bhXIBMQt9OqTRKTZ0NKoUgVzSQ5t)

tips: 默认加密形式: ENC(加密后密码)

6. jasypt 3.0.3 避坑指南

官网目前是 3.0.3 版本,和 2.0.0 相比默认的算法变了,支持的jdk版本也变了

默认加密方法如下:

@Test void newPwd() { PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); SimpleStringPBEConfig config = new SimpleStringPBEConfig(); config.setPassword("thisisapasswordsecret"); config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256"); // 算法做了更新 config.setKeyObtentionIterations("1000"); config.setPoolSize("1"); config.setProviderName("SunJCE"); config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator"); config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator"); config.setStringOutputType("base64"); encryptor.setConfig(config); System.out.println(encryptor.encrypt("you origin password")); }

另外, jdk 低于 8u161 版本的两个安全 jar 包 $JAVA_HOME/jre/lib/security/local_policy.jar $JAVA_HOME/jre/lib/security/US_export_policy.jar 需要去官网更新,地址 https://www.oracle.com/java/technologies/javase-jce8-downloads.html

最新回复(0)