文章字数:290,阅读全文大约需要1分钟
application.properties
中经常会放账户密码数据库连接地址等敏感信息,可能会造成信息的泄露。使用jasypt
可以加密解密配置文件。
引入
1 2 3 4 5
| <dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>1.5</version> </dependency>
|
使用
- 通过密钥生成密文
1
| java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI password=G0CvDz7oJn6 algorithm=PBEWithMD5AndDES input=root
|
结果
1 2 3 4 5 6 7 8 9 10
| ----ENVIRONMENT----------------- Runtime: Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 25.171-b11
----ARGUMENTS------------------- input: root algorithm: PBEWithMD5AndDES password: G0CvDz7oJn6
----OUTPUT---------------------- Gvkoz+sbFWiRe3ECtizV1A==
|
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
| import org.jasypt.util.text.BasicTextEncryptor; import java.util.UUID;
public class testTest { public static void main(String[] args) { testTest t = new testTest(); t.getPass(); }
public void getPass() { BasicTextEncryptor stringEncryptor = new BasicTextEncryptor(); stringEncryptor.setPassword("tfa46e505nh4565e5o8adjg4a8e01by");
String url = stringEncryptor.encrypt("url"); String name = stringEncryptor.encrypt("username"); String password = stringEncryptor.encrypt("pwd"); System.out.println("-----------------url------------------"); System.out.println("ENC("+url+")"); System.out.println("-----------------name------------------"); System.out.println("ENC("+name+")"); System.out.println("-----------------pwd------------------"); System.out.println("ENC("+password+")");
password = password.replace("ENC(",""); password = password.replace(")",""); String decrypted = stringEncryptor.decrypt(password); System.out.println("-----------------decrypt------------------"); System.out.println(decrypted); String uuid = UUID.randomUUID().toString().replaceAll("-",""); System.out.println("-----------------uuid------------------"); System.out.println(uuid); } }
|
- 配置文件
1 2 3 4 5
| # 加密所需的salt(盐),和生成密文时使用的要一样 jasypt.encryptor.password=tfa46e505nh4565e5o8adjg4a8e01by # 加密后的密文,使用ENC(...)包裹 spring.datasource.username=ENC(6eaMh/RX5oXUVca9ignvtg==) spring.datasource.password=ENC(6eaMh/RX5oXUVca9ignvtg==)
|
- 开启加密
项目里没有使用@SpringBootApplication或者@EnableAutoConfiguration,可以手动在Configuration类上添加注解@EnableEncryptableProperties,来在整个环境的属性启用属性加密。