Spring 中使用jasypt对配置文件(.properties)中密码加密

来源:互联网 发布:魔法王座神器升级数据 编辑:程序博客网 时间:2024/05/19 23:17

spring配置中经常使用placeholder来加载一个应用配置文件(.properties),但是其中的各种密码以明文显示出来总该是不好。

不过可以利用jasypt这个框架来扩展这个加密功能,需要用到jasypt中的icu4j-version.jar、jasypt-version-lite.jar、jasypt-version.jar和jasypt-spring31-version.jar

首先,注释掉原有的placeholder加载方式

[html] view plain copy
  1. <!--<context:property-placeholder location="/WEB-INF/config.properties"/> -->  
然后使用jasypt为spring相应版本实现的placeholder
[html] view plain copy
  1. <!-- decrypt password in config.properties -->  
  2.     <bean id="environmentVariablesConfiguration"  
  3.         class="org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig">  
  4.         <property name="algorithm" value="PBEWithMD5AndDES" />  
  5.         <property name="password" value="root" />  
  6.     </bean>  
  7.     <bean id="configurationEncryptor" class="org.jasypt.encryption.pbe.StandardPBEStringEncryptor">  
  8.         <property name="config" ref="environmentVariablesConfiguration" />  
  9.     </bean>  
  10.     <bean id="propertyConfigurer"  
  11.         class="org.jasypt.spring31.properties.EncryptablePropertyPlaceholderConfigurer">  
  12.         <constructor-arg ref="configurationEncryptor" />  
  13.         <property name="locations">  
  14.             <list>  
  15.                 <value>/WEB-INF/config.properties</value>  
  16.             </list>  
  17.         </property>  
  18.         <property name="fileEncoding" value="utf-8" />  
  19.     </bean>   
最后,修改.properties配置中的明文密码为密文,这个需要自己写一个main方法
[java] view plain copy
  1. public static void main(String[] args) {  
  2.         //PBEWithMD5AndDES  
  3.         BasicTextEncryptor encryptor = new BasicTextEncryptor();  
  4.         encryptor.setPassword("root");  
  5.         String encrypted = encryptor.encrypt("xxxx");  
  6.         System.out.println(encrypted);  
  7.     }  
然后将输出的密文替换原来的密码
[html] view plain copy
  1. jdbc.password=ENC(jHv0WdiTLJFmOO08RQtUpg==)  

这样的密文虽然还是很容易被decode出来,但终究不是明文显示。

个人认为最好的办法可能是 自己去实现一个spring的 place holder,利用md5来匹配配置文件中的密文是否正确。


0 0
原创粉丝点击