使用Jasypt对数据库配置文件进行加密
2015-07-09 13:46
821 查看
在Spring配置文件中常使用占位符(placeholder )来加载资源文件,常常一些资源文件都是已明文形式存放的,比如jdbc配置信息等,从系统安全角度来说,这些信息已明文形式显示总是不好。今天接触Jasypt,查了一些资料学习了下。Jasypt 是sourceforge.net上的一个开源项目,是一个Java库。更多介绍自行google吧。
第一步,加入Jasypt依赖。这里我们使用maven。
加密:
解密:
与Spring集成。在Spring的配置文件里面加入如下代码:
在看一下jdbc.properties文件:
记得在你的密文前加上ENC前缀,并用()包起来。为什么要这样写,查看源码便知:
这样子在启动Spring容器的时候就会读取到加密的值就会自动进行解密了。
第一步,加入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容器的时候就会读取到加密的值就会自动进行解密了。
相关文章推荐
- mysql查询表中文显示乱码的解决办法
- 使用HAProxy、PHP、Redis和MySQL支撑10亿请求每周架构细节
- mysql忘记密码怎么改
- Ubuntu 安装 Redis(转的配置)
- mysql悲观锁总结和实践
- 在Ubuntu中安装Redis
- mydumper备份mysql数据库示例
- 如何清除数据库重复数据
- mysql字符串替换
- 转载Mysql的乱码问题
- MySQL与Oracle 差异比较之数据类型比较
- MySQL与Oracle 差异比较之基本语法的比较
- MySQL与Oracle 差异比较之函数比较
- MySQL安装和SQL语句入门
- 安装oracle数据库时的报错处理[INS-35172]
- MySQL分库分表
- Windows下java memcached 使用
- sql时间天数操作
- mysql 主master 从 slaver 复制 配置详细
- 关于CoreData和SQLite多线程访问时的线程安全问题