配置文件加密和数据库一些内容的加密存储
背景
在一些项目的设计中,密码等一些重要的东西显然是不能出现在代码和数据库中的。如果出现,这显然是不符合安全规定的。所以我们就需要加密存储和解密取出,这就用了本文的方法。
方法
本文使用Encrptor方法进行加密解密,好处是只要定义这个类以后。项目内部任意字符串都可以通过调用Encrptor方法进行加密解密,包括数据库密码。做到一步定义,万事无忧。
- 在配置文件中存放密钥,这里密钥随便设置
jasypt.encryptor.password=ABCDE12345
- 新建一个配置类ApplicationContextUtil实现ApplicationContextAware,获取application.properties的配置内容
@Configuration
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public static <T> T get(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
public static Object get(String name) {
return applicationContext.getBean(name);
}
}
- 创建明文加解密类 Encryptor
public class Encryptor {
public static String getEncryptorPassword() {
Environment environment = ApplicationContextUtil.get(Environment.class);
String encryptorPassword = environment.getProperty("jasypt.encryptor.password");
return encryptorPassword;
}
public static String encrypt(String orgStr) {
BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
textEncryptor.setPassword(getEncryptorPassword());
return textEncryptor.encrypt(orgStr);
}
public static String decrypt(String orgStr) {
BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
textEncryptor.setPassword(getEncryptorPassword());
return textEncryptor.decrypt(orgStr);
}
}
- 做完以上步骤就算完成了,由于是静态方法,只需要“哪里不会点哪里了”。下面给几个示例。
//密码加密存储
Encryptor.encrypt(systemUser.getPassword())
//登陆时密码解密取出
Encryptor.decrypt(systemUser.getPassword())
另外对于想加密配置文件,比如数据库密码想以密文显示,只需要先把原密码加密输出
System.out.println("ENC(" + textEncryptor.encrypt("password") + ")");
得到密文后在配置文件里这样写,系统自动就能读懂,你的密码是加密过的了
spring.datasource.password=ENC(得到的加密过的密文)
可能出现的问题
Failed to bind properties under
Description:
Failed to bind properties under 'spring.datasource.password' to java.lang.String:
Reason: Failed to bind properties under 'spring.datasource.password' to java.lang.String
Update your application's configuration
解决办法: 发现是3.0.3
更改了默认的加密算法,最后的办法是把版本降到2.1.2