总结摘要
本文介绍了如何在 Gradle 中添加 Jasypt 加解密命令,用于保护 Spring 配置文件中的敏感信息。作者通过自定义 Gradle 任务 JasyptCliTask,实现了基于 Jasypt 的字符串加密和解密功能。使用时,可以通过命令行参数指定待处理的字符串和加密密钥,执行 gradle encrypt 或 gradle decrypt 命令完成加解密操作。该方法不依赖第三方插件,避免了插件维护问题,同时提供了灵活的加密配置选项。
在 Spring 开发中,为了保护配置文件中的敏感信息,比如数据库密码、云密钥等数据,需要对配置进行加密,而jasypt-spring-boot
就为我们提供了这样的实现。
在 maven 中我们可以使用mvn jasypt:encrypt-value
或者mvn jasypt:decrypt-value
通过命令行对数据进行加解密,gradle 也有相应的工具:
但都不是官方维护,有一定的风险,出了问题解决起来比较麻烦。
添加 gradle 命令
经过查询资料,我们可以在 gradle 里面定义相关的命令:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
| // jasypt加解密任务
abstract class JasyptCliTask extends JavaExec {
@Input
String input
@Input
String password
@Input
Boolean isEncryptionCli
@TaskAction
@Override
void exec() {
def jasyptCliClass = isEncryptionCli ? 'JasyptPBEStringEncryptionCLI' : 'JasyptPBEStringDecryptionCLI'
if (isEncryptionCli) {
println("plain text: \n${input}\n")
println("cipher text:")
} else {
println("cipher text: \n${input}\n")
println("plain text:")
}
project.javaexec {
classpath = project.sourceSets.main.runtimeClasspath
mainClass.set('org.jasypt.intf.cli.' + jasyptCliClass)
args = [
'input="' + input + '"',
'password="' + password + '"',
'algorithm=PBEWITHHMACSHA512ANDAES_256',
'ivGeneratorClassName=org.jasypt.iv.RandomIvGenerator',
'verbose=false'
]
}
}
}
tasks.register('encrypt', JasyptCliTask) {
group 'jasypt'
description 'Encrypts a string using the Jasypt CLI'
input = project.properties['input'] ?: null
password = project.properties['password'] ?: System.getenv('JASYPT_ENCRYPTOR_PASSWORD') ?: null
isEncryptionCli = true
}
tasks.register('decrypt', JasyptCliTask) {
group 'jasypt'
description 'Decrypts a string using the Jasypt CLI'
input = project.properties['input'] ?: null
password = project.properties['password'] ?: System.getenv('JASYPT_ENCRYPTOR_PASSWORD') ?: null
isEncryptionCli = false
}
|
使用
1
2
3
4
5
6
7
| # 加密
# 输出结果:giBl8R01EFIFIUlZYFA1HBq501gm5QnQcsuK2veUk4EWdtuHcMsR9CQjiRy8CPsW
# 同一段明文和密钥每次加密结果不一定一样
gradle encrypt -Pinput=123456abcde -Ppassword=y04WKoRO75uMilkYCcpIU6nFVxsawQzv
# 解密
gradle decrypt -Pinput=giBl8R01EFIFIUlZYFA1HBq501gm5QnQcsuK2veUk4EWdtuHcMsR9CQjiRy8CPsW -Ppassword=y04WKoRO75uMilkYCcpIU6nFVxsawQzv
|
参考资料