您的位置:首页 > 编程语言 > Java开发

Spring Boot使用jasypt对配置文件中敏感信息进行加密

2020-09-01 17:24 232 查看

日常使用中,数据库、redis、kafka等信息一般会配在配置文件中,而且以明文的方式,这样就很不安全,容易造成重要信息的泄露。
正好之前我们做项目的时候用到 jasypt 进行加密存储。
最近需要修改数据库密码,正好记录一下这个知识点。

1、引入依赖

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

2、加密

在 maven 仓库找到 jasypt 的 jar 包,

打开命令行窗口

命令为:

java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI password=123456 algorithm=PBEWithMD5AndDES input=lixj
  • password:加密的私钥
  • input:要加密的信息

如图所示,私钥为123456,lixj 加密后的密文为:resHmHRaVO6d7CcyJLHv8Q==
如果不喜欢可以执行多次,每次生成的密文都不一样。

3、配置

将加密后的信息配置在配置文件,使用 ENC 关键字。

添加 @EnableEncryptableProperties

应用启动时需要添加以下启动参数,不然会解密不出来,导致启动失败。

-Djasypt.encryptor.password=123456 -Djasypt.encryptor.algorithm=PBEWithMD5AndDES

4、解密

java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI  password=123456 algorithm=PBEWithMD5AndDES input="resHmHRaVO6d7CcyJLHv8Q=="

5、java 代码实现加解密

import org.jasypt.intf.service.JasyptStatelessService;

public enum JasyptEncryptUtil {
/**
* 唯一实例,使工具类单例化
*/
INSTANCE;

private static JasyptStatelessService jasyptStatelessService = new JasyptStatelessService();

// 加密
public static String encrypt(String input, String password, String algorithm) {
return jasyptStatelessService.encrypt(input, password, null, null, algorithm, null, null, null, null,
null, null, null, null, null, null,
null, null, null, null, null, null, null);
}

// 解密
public static String decrypt(String input, String password, String algorithm) {
return jasyptStatelessService.decrypt(input, password, null, null, algorithm, null, null, null, null,
null, null, null, null, null, null, null,
null, null, null, null, null,null);
}

/**
* 使用默认加密算法:PBEWithMD5AndDES
* 加密
* @param input    要加密的内容
* @param password 密钥
* @return
*/
public static String encrypt(String input, String password) {
return encrypt(input, password, "PBEWithMD5AndDES");
}

/**
* 使用默认加密算法:PBEWithMD5AndDES
* 解密
* @param input   要解密的内容
* @param password  密钥
* @return
*/
public static String decrypt(String input, String password) {
return decrypt(input, password, "PBEWithMD5AndDES");
}

public static void main(String[] args) {
System.out.println(encrypt("lixj", "123456"));
System.out.println(decrypt("9HhTbI9i6bh7D2tAVDYblA==", "123456"));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: