Springboot实现ENC加密
- 1、导入依赖
- 2、配置加密秘钥(盐)
- 3、获取并配置密文
- 4、重启项目测试
- 5、自定义前缀、后缀
- 6、自定义加密方式
1、导入依赖
关于版本,需要根据spring-boot版本,自行修改
com.github.ulisesbocchio jasypt-spring-boot-starter 3.0.5 2、配置加密秘钥(盐)
可以在配置文件中自定义一个加密秘钥(盐),
jasypt: encryptor: password: serfgsjf
3、获取并配置密文
在测试类中,对密码进行加密,获取密文
@SpringBootTest @RunWith(SpringRunner.class) public class myTest { @Resource private StringEncryptor jasyptStringEncryptor; @Test public void encodeMysql() { System.out.println( "mysql密码加密密文:" + jasyptStringEncryptor.encrypt("123456") ); System.out.println("解密密文:" + jasyptStringEncryptor.decrypt(jasyptStringEncryptor.encrypt("123456"))); } }
运行结果
配置密码
4、重启项目测试
5、自定义前缀、后缀
jasypt: encryptor: password: serfgsjf property: prefix: ABC( # 自定义前缀 suffix: )abc # 自定义后缀
配置密码
spring: datasource: password: ABC(W6FAAdoHve471ySHYQ7C5g8i56FWbLsivDBpNMWaAsq5RfthfC616aOPA4j0LKUG)abc
6、自定义加密方式
如果不想使用默认的加密方式,支持自定义
新建配置类
package com.hyq.config; import org.jasypt.encryption.StringEncryptor; import org.jasypt.encryption.pbe.PooledPBEStringEncryptor; import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MyEncryptorCfg { @Bean(name = "myStringEncryptor") public StringEncryptor myStringEncryptor() {PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); SimpleStringPBEConfig config = new SimpleStringPBEConfig(); // 用于设置加密密钥。密钥是用于加密和解密字符串的关键信息。 config.setPassword("serfgsjf"); // 加密算法的名称。此处选择了PBEWithMD5AndDES算法,这是一种对称加密算法。 config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256"); // 用于设置加密时迭代次数的数量,增加迭代次数可以使攻击者更难进行密码破解。 config.setKeyObtentionIterations("1000"); // 加密器池的大小。池是一组加密器实例,可确保加密操作的并发性。 config.setPoolSize("1"); // 用于设置JCE(Java Cryptography Extension)提供程序的名称。 config.setProviderName("SunJCE"); // 用于设置生成盐的类名称。在此配置中,我们使用了org.jasypt.salt.RandomSaltGenerator,表示使用随机生成的盐。 config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator"); // 用于设置Jasypt使用的初始化向量(IV)生成器的类名。初始化向量是在加密过程中使用的一个固定长度的随机数,用于加密数据块,使每个数据块的加密结果都是唯一的。在此配置中,我们使用了org.jasypt.iv.RandomIvGenerator类,该类是一个随机生成器,用于生成实时随机IV的实例。这样可以确保每次加密的IV都是唯一的,从而增加加密强度。 config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator"); // 指定加密输出类型。在此配置中,我们选择了base64输出类型。 config.setStringOutputType("base64"); encryptor.setConfig(config); return encryptor; } }
使用自定义的方案生成密文
@SpringBootTest @RunWith(SpringRunner.class) public class myTest { @Autowired private MyEncryptorCfg myEncryptorCfg; @Test public void encodePwd() { System.out.println("加密密文:" + myEncryptorCfg.myStringEncryptor().encrypt("123456")); System.out.println("解密明文:" + myEncryptorCfg.myStringEncryptor().decrypt(myEncryptorCfg.myStringEncryptor().encrypt("123456"))); } }
运行结果
配置密码
spring: datasource: password: ABC(1PHEw/VIlntBkkQP9ZnyjcXeH2BinJYhoI/0e2jKxXb2W7C/Nj6R6Lcv6opWDBhu)abc
测试