1. 程式人生 > >對jdbc.properties中的密碼加密

對jdbc.properties中的密碼加密

為什麼對jdbc檔案加密:如果jdbc中的使用者名稱和密碼配置為明文  這樣別人就很容易連線上伺服器  為了安全考慮 將jdbc中的密碼配成加密檔案

一、建立加密和解密的Util

二、當我們在spring中配置了jdbc的連線資訊後 在這之前我們要將密碼解密  然後再進行資料庫的連線

    <!-- 密文  此段程式碼要加在連線資料庫之前-->
     <bean id="propertyConfigurerS"  //id   自定義  class為PasswordEncryptConfigurer的路徑
          class="com.aa.app.cib.commonUtil.PasswordEncryptConfigurer"> 
          <property name="ignoreUnresolvablePlaceholders" value="true"/>
             <property name="ignoreResourceNotFound" value="true"/>
             <property name="locations">
               <list>
                  <value>/WEB-INF/jdbc.properties</value>  //這是jdbc的路徑
               </list>
             </property>
     </bean> 

注意:如果要生成密文 請到對應的Util生成  

話不多說,下面上程式碼

注意:在jdbc.properties中  密文前面要加上{DES}  否則就不會作為密文解析

package com.jdbcDes;

import java.util.Properties;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

public class PasswordEncryptConfigurer extends PropertyPlaceholderConfigurer {

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException {
        System.out.println("正在解密系統檔案...");
        try {
            String JdPassword = props.getProperty("jdbc.password");
            // rk----------------------
            if (JdPassword != null &&JdPassword .startsWith("{DES}")) {

               JdPassword = JdPassword .substring("{DES}".length());
                //解密  password
                JdPassword = EncryptUtil.decodeString(JdPassword);
            }

           //將解密後的密碼放入Properties中
            props.setProperty("jdbc.password", JdPassword);
             super.processProperties(beanFactory, props);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BeanInitializationException(e.getMessage());
        }
    }
}

然後用MD5加密,或者其他的加密工具