1. 引入依赖
在项目的 pom.xml 文件中引入以下依赖,用于支持 Jasypt 加密功能:
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.4</version>
</dependency>
2. 在配置文件中添加Jasypt配置
在 application.yml 或 application.properties 中添加以下配置:
jasypt:
encryptor:
# 加密器的密码,用于解密配置文件中的加密内容。
# 请确保此密码足够复杂且妥善保管,避免泄露。
password: hduOJTi0Y4kLNO8EQ/DCWA==
# 加密算法,使用PBEWithMD5AndDES算法对数据进行加密和解密。
# 可根据需要更换为其他支持的加密算法。
algorithm: PBEWithMD5AndDES
# 配置初始化向量生成器,解决Jasypt 3.0.3及以上版本启动报错的问题。
# NoIvGenerator表示不使用向量生成器(即无向量)。
iv-generator-classname: org.jasypt.iv.NoIvGenerator
3. 创建加密密码生成类
编写一个工具类,用于将明文密码加密成密文:
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
/**
* 加密密码生成工具类
* @author Gurucyy
*/
public class PasswordEncryptor {
public static void main(String[] args) {
// 明文密码
String password = "tHMfKlK6H4VXH#!r%%9m";
// 加密秘钥,与配置文件中的 jasypt.encryptor.password 保持一致
String secretKey = "hduOJTi0Y4kLNO8EQ/DCWA==";
// 加密算法,与配置文件中的 jasypt.encryptor.algorithm 保持一致
String algorithm = "PBEWithMD5AndDES";
// 创建加密器对象
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword(secretKey);
encryptor.setAlgorithm(algorithm);
// 执行加密操作
String encryptedPassword = encryptor.encrypt(password);
System.out.println("最终生成的加密串:" + encryptedPassword);
}
}
4. 替换配置文件中的明文密码
将配置文件中的明文密码替换为加密后的密文。例如:
# 原始配置(明文密码)
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: tHMfKlK6H4VXH#!r%%9m
# 修改后的配置(加密密码)
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: ENC(NW9H3xDZNC1zL/QKDJd8Ew==) # 这里的内容是生成的加密串
5. 重启Java项目,验证配置文件中加密内容的解密功能是否正常工作。
注意事项:
jasypt.encryptor.password和jasypt.encryptor.algorithm在生成加密串时必须与配置文件中保持一致。- 替换后的密码需要使用
ENC()包裹,以便Jasypt在启动时自动解密。 - 如果需要更换加密算法或秘钥,请同时更新工具类和配置文件中的相关配置。
240

被折叠的 条评论
为什么被折叠?



