一、前言
有时在实际应用中,我们可能需要使用到一些秘钥,针对某些资源文件中的内容通常情况下是明文显示,安全性就比较低一些,比如redis登陆密码以及第三方的密钥等等一览无余,这时就可以使用jasypt来实现加解密。
二、如何实现?
1.引入Maven jar包
<dependency><groupId>com.github.ulisesbocchio</groupId><artifactId>jasypt-spring-boot-starter</artifactId><version>3.0.3</version>
</dependency>
2.application.yml文件中增加jasypt的秘钥(该秘钥自定义的):
jasypt:encryptor:#加密秘钥password: Eb12kitulv73I2p21XI507
3.接着写个测试类。
@RestController
public class IndexController {@Autowiredprivate StringEncryptor encryptor;/*** 测试jasypt加密解密*/@GetMapping("/test")public void testJasypt() {String password = "12345678";String encryptPwd = encryptor.encrypt(password);System.out.println("加密::" + encryptPwd);System.out.println("解密:" + encryptor.decrypt(encryptPwd));}}
jasypt由于其使用的是PBEWithMD5AndDES加密方式,所以每次加密出来的结果都不一样,但是解密都是一样的,所以很适合对数据进行加密。
4.将加解密秘钥放在配置文件中是不安全的,有如下几种解决办法:
1)、在启动类上赋值秘钥:
@SpringBootApplication
public class ProviderApplication {public static void main(String[] args) {/** 配置加解密秘钥,与配置文件的密文分开放 */System.setProperty("jasypt.encryptor.password", "suntree@qwe!!");SpringApplication.run(ProviderApplication.class, args);}}
- 自定义StringEncryptor
/*** 配置StringEncryptor*/@Bean("jasyptStringEncryptor")public StringEncryptor stringEncryptor() {PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();SimpleStringPBEConfig config = new SimpleStringPBEConfig();config.setPassword("suntree@qwe!!");config.setAlgorithm("PBEWithMD5AndDES");config.setKeyObtentionIterations("1000");config.setPoolSize("1");config.setProviderName("SunRTE");config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");config.setIvGeneratorClassName("org.jasypt.salt.NoOpIVGenerator");config.setStringOutputType("base64");encryptor.setConfig(config);return encryptor;}