1.jasypt介绍java
官网:http://www.jasypt.org/,里面有介绍jasypt是干吗的,官网记得介绍:Jasypt is a java library which allows the developer to add basic encryption capabilities to his/her projects with minimum effort, and without the need of having deep knowledge on how cryptography works.大体意思是:Jasypt是一个Java库,容许开发者基本的加密功能添加到你所开发的项目以最少的投入,而不须要有密码技术是如何工做的很深的造诣。因此只要使用就行。算法
2.项目实际开发spring
2.1 添加jar包sql
通常项目是使用maven管理,因此咱们首先应该到,maven repository库里找到版本信息:maven
<dependency> <groupId>org.jasypt</groupId> <artifactId>jasypt</artifactId> <version>1.9.2</version> </dependency>
把上面的信息添加到pom.xml文件中进行。ide
2.2 配置相关文件xmlthis
第一种方式:配置xml文件加密
<bean id="environmentVariablesConfiguration" class="org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig"> <property name="algorithm" value="PBEWithMD5AndDES" /> <property name="password" value="root" /> </bean> <bean id="configurationEncryptor" class="org.jasypt.encryption.pbe.StandardPBEStringEncryptor"> <property name="config" ref="environmentVariablesConfiguration" /> </bean> <bean id="propertyConfigurer" class="org.jasypt.spring31.properties.EncryptablePropertyPlaceholderConfigurer"> <constructor-arg ref="configurationEncryptor" /> <property name="locations"> <list> <value>/WEB-INF/config.properties</value> </list> </property> <property name="fileEncoding" value="utf-8" /> </bean>
最后,修改.properties配置中的明文密码为密文,这个须要本身写一个main方法,对其进行加密,而后把加密的结果,填写到.properties中:spa
public static void main(String[] args) { //PBEWithMD5AndDES BasicTextEncryptor encryptor = new BasicTextEncryptor(); encryptor.setPassword("root"); String encrypted = encryptor.encrypt("xxxx"); System.out.println(encrypted); }
最后更改.properties的信息:code
jdbc.password=ENC(jHv0WdiTLJFmOO08RQtUpg==)
2.2第二种方式:修改配置文件
<bean id="encryptPropertyPlaceholderConfigurer" class="com.util.EncryptPropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:config.properties</value> </list> </property> <!--对配置文件中的指定属性进行解密 --> <property name="encryptedProps"> <set> <value>orcl.password</value> <value>sql.password</value> </set> </property>
建立一个类:
public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer { private Set<String> encryptedProps = Collections.emptySet(); public void setEncryptedProps(Set<String> encryptedProps) { this.encryptedProps = encryptedProps; } @Override protected String convertProperty(String propertyName, String propertyValue) { if (encryptedProps.contains(propertyName)) { return EncryptUtil.decode(propertyValue); } return super.convertProperty(propertyName, propertyValue); } }
建立一个util加密算法:
网上好多,这里不列举,只要能进行加密和进行解密的就行,不建议使用MD5,由于MD5是单向加密算法。