jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://xxx.xxx.xxx.xxx.:3306/xxx?useUnicode=true&characterEncoding=utf8
jdbc.username=4YR65mbD1+c=
jdbc.password=mcWsjuuMs6MrfnkytW37XA==
package com.sane.o2o.util;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
public class EncryptPropertyPlaceHolderConfiger extends PropertyPlaceholderConfigurer {
private String[] encryptPropNames={"jdbc.username","jdbc.password"};
@Override
protected String convertProperty(String propertyName, String propertyValue) {
if(isEncryptProp(propertyName)){
String descryptValue=DesUtil.getDecryptString(propertyValue);
return descryptValue;
}else{
return propertyValue;
}
}
private boolean isEncryptProp(String propName){
return Arrays.asList(encryptPropNames).contains(propName);
}
}
public class DesUtil {
private static Key key;
private static String KEY_SALT="自己填寫隨意的鹽值";
private static String CHARSETNAME="UTF-8";
private static String ALGORITHM="DES";
static {
try {
//生產(chǎn)DES算法對象
KeyGenerator keyGenerator=KeyGenerator.getInstance(ALGORITHM);
//運行SHA1安全策略
SecureRandom secureRandom=SecureRandom.getInstance("SHA1PRNG");
//設置秘鑰種子
secureRandom.setSeed(KEY_SALT.getBytes());
//初始化基于SHA1的算法對象
keyGenerator.init(secureRandom);
key=keyGenerator.generateKey();
}catch (Exception e){
throw new RuntimeException(e.getMessage());
}
}
public static String getEncryptString(String str){
try {
BASE64Encoder base64Encoder=new BASE64Encoder();
//按照UTF-8編碼
byte[] bytes=str.getBytes(CHARSETNAME);
//獲取加密對象
Cipher cipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE,key);
//加密
byte[] doFinal=cipher.doFinal(bytes);
return base64Encoder.encode(doFinal);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
public static String getDecryptString(String str){
BASE64Decoder base64Decoder=new BASE64Decoder();
try {
byte[] bytes=base64Decoder.decodeBuffer(str);
Cipher cipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE,key);
byte[] doFinal=cipher.doFinal(bytes);
return new String(doFinal,CHARSETNAME);
}catch (Exception ex){
throw new RuntimeException(ex.getMessage());
}
}
public static void main(String args[]){
System.out.println(getEncryptString("root"));
System.out.println(getDecryptString("4YR65mbD1+c="));
System.out.println(getEncryptString("1Qaz#0Okm"));
System.out.println(getDecryptString("mcWsjuuMs6MrfnkytW37XA=="));
}
}
<bean id="propertyConfigurer" class="com.sane.o2o.util.EncryptPropertyPlaceHolderConfiger">
<property name="ignoreResourceNotFound" value="true"></property>
<property name="fileEncoding" value="UTF-8"></property>
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>