您的位置:首页 > 数据库

使用Jasypt对数据库配置文件进行加密

2015-07-09 13:46 821 查看
在Spring配置文件中常使用占位符(placeholder )来加载资源文件,常常一些资源文件都是已明文形式存放的,比如jdbc配置信息等,从系统安全角度来说,这些信息已明文形式显示总是不好。今天接触Jasypt,查了一些资料学习了下。Jasypt 是sourceforge.net上的一个开源项目,是一个Java库。更多介绍自行google吧。

第一步,加入Jasypt依赖。这里我们使用maven。

<dependency>
<groupId>org.jasypt</groupId>
<artifactId>jasypt</artifactId>
<version>1.8</version>
</dependency>


加密:

@Test
public void encrypt() {
// 创建加密器
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
// 配置
EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
config.setAlgorithm("PBEWithMD5AndDES");// 加密算法
config.setPassword("fuyung");// 系统属性值
encryptor.setConfig(config);

String plaintext = "root"; //明文
String ciphertext = encryptor.encrypt(plaintext); // 加密
System.out.println(plaintext + " : " + ciphertext);// 运行结果:root : 8y9G4kIZQuCHB78mMJNkHw==
}


解密:

@Test
public void decrypt() {
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
config.setAlgorithm("PBEWithMD5AndDES");
config.setPassword("fuyung");
encryptor.setConfig(config);
String ciphertext = "8y9G4kIZQuCHB78mMJNkHw==";// 密文

//解密
String plaintext = encryptor.decrypt(ciphertext); // 解密
System.out.println(ciphertext + " : " + plaintext);// 运行结果:8y9G4kIZQuCHB78mMJNkHw== : root
}


与Spring集成。在Spring的配置文件里面加入如下代码:

<bean id="propertyConfigure"
class="org.jasypt.spring.properties.EncryptablePropertyPlaceholderConfigurer">
<constructor-arg ref="configurationEncryptor"/>

<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
<property name="ignoreResourceNotFound" value="true"/>
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<bean id="configurationEncryptor"
class="org.jasypt.encryption.pbe.StandardPBEStringEncryptor">
<property name="config" ref="environmentVariablesConfiguration"/>
</bean>

<bean id="environmentVariablesConfiguration"
class="org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig">
<property name="algorithm" value="PBEWithMD5AndDES"/>
<property name="password" value="clm"/>
</bean>


在看一下jdbc.properties文件:

jdbc.username=ENC(kpKWmxAX2LMUqqkKPCulpTimxznTDxXw)
jdbc.password=ENC(Wg/U1YMQOznH4WyP7HpTTJL0v1KGFLIC)


记得在你的密文前加上ENC前缀,并用()包起来。为什么要这样写,查看源码便知:



这样子在启动Spring容器的时候就会读取到加密的值就会自动进行解密了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: