Spring中管理數據源,加密和解密賬號密碼的方法

開始有一篇關於SSH框架上加密、解密讀取properties上的文件,現使用另一種方式來實現


首先:工具類DESUtils

import java.security.Key;
import java.security.SecureRandom;
 
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
 
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
 
public class DESUtils {
 
    private static Key key;
    private static String KEY_STR = "myKey";// 密鑰
    private static String CHARSETNAME = "UTF-8";// 編碼
    private static String ALGORITHM = "DES";// 加密類型
 
    static {
        try {
            KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
            generator.init(new SecureRandom(KEY_STR.getBytes()));
            key = generator.generateKey();
            generator = null;
        } catch (Exception e) {
            // TODO: handle exception
            throw new RuntimeException(e);
        }
    }
 
    /**
     * 對str進行DES加密
     * 
     * @param str
     * @return
     */
    public static String getEncryptString(String str) {
        BASE64Encoder base64encoder = new BASE64Encoder();
        try {
            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) {
            // TODO: handle exception
            throw new RuntimeException(e);
        }
    }
 
    /**
     * 對str進行DES解密
     * 
     * @param str
     * @return
     */
    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 e) {
            // TODO: handle exception
            throw new RuntimeException(e);
        }
    }
 
}


工具類:EncryPtPropertyPlaceholderConfigurer

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
 
/**
 * 繼承PropertyPlaceholderConfigurer定義支持密文版屬性的屬性配置器
 * 
 * @author moziqi
 * 
 */
public class EncryptPropertyPlaceholderConfigurer extends
        PropertyPlaceholderConfigurer {
    private String[] encryptPropNames = { "userName", "password" };
 
    @Override
    protected String convertProperty(String propertyName, String propertyValue) {
        if (isEncryptProp(propertyName)) {
            String decryptValue = DESUtils.getDecryptString(propertyValue);
            System.out.println(propertyName + "解密內容:" + decryptValue);
            return decryptValue;
        } else {
            return propertyValue;
        }
    }
 
    /**
     * 判斷是否是加密的屬性
     * 
     * @param propertyName
     * @return
     */
    private boolean isEncryptProp(String propertyName) {
        for (String encryptpropertyName : encryptPropNames) {
            if (encryptpropertyName.equals(propertyName))
                return true;
        }
        return false;
    }
}

測試的properties文件

dbName=sampledb
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/${dbName}
#userName=root
#password=123456
userName=WnplV/ietfQ=
password=QAHlVoUc49w=


spring中的數據源bean配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <!--1.使用傳統的PropertyPlaceholderConfigurer引用屬性文件 -->
    <!-- bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:fileEncoding="utf-8"> <property name="locations"> <list> <value>classpath:com/baobaotao/placeholder/jdbc.properties</value> 
        </list> </property> </bean -->
 
    <!--2.使用context命名空間的配置引用屬性文件 -->
    <!--context:property-placeholder location="classpath:com/baobaotao/placeholder/jdbc.properties"
        file-encoding="utf8"/> <bean id="utf8" class="java.lang.String"> <constructor-arg 
        value="utf-8"></constructor-arg> </bean -->
 
    <!--3.使用加密版的屬性文件 -->
    <bean class="com.spring.util.EncryptPropertyPlaceholderConfigurer"
        p:location="classpath:jdbc.properties" p:fileEncoding="utf-8" />
 
    <context:component-scan base-package="com.spring.*" />
 
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close" p:driverClassName="${driverClassName}" p:url="${url}"
        p:username="${userName}" p:password="${password}" />
</beans>




發佈了22 篇原創文章 · 獲贊 35 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章