对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.skysz.framework.security;

import java.util.Properties;

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

import com.skysz.framework.spring.config.PropertyPlaceholderConfigurer;
import com.skysz.framework.utils.encrypt.EncryptUtil;

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());
        }
    }
}

package com.skysz.framework.common.util;

import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * DES加密类
 * @author Tom Koo
 * @since 1.0
 */
public class DesEncrypt {

    private final static String enCoding = "utf-8";

    private final byte[] DESkey = new byte[128];// 设置密钥

    private final byte[] DESIV = new byte[8];// 设置向量

    private AlgorithmParameterSpec iv = null;// 加密算法的参数接口,IvParameterSpec是它的一个实现

    private Key key = null;

    public DesEncrypt() {
        this(new byte[] {});
    }

    public DesEncrypt(String desKey) {
        this(desKey.getBytes());
    }

    public DesEncrypt(byte[] desKey) {
        try {
            for (int i = 0; desKey != null && i < desKey.length && i < 8; i++) {
                DESkey[i] = desKey[i];
            }
            DESKeySpec keySpec = new DESKeySpec(DESkey);// 设置密钥参数
            iv = new IvParameterSpec(DESIV);// 设置向量
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
            key = keyFactory.generateSecret(keySpec);// 得到密钥对象
        } catch (Exception e) {
            throw new RuntimeSecurityException(e);
        }

    }

    public String encode(String data) {
        try {
            Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher
            enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式,给出密钥和向量
            byte[] pasByte = enCipher.doFinal(data.getBytes(enCoding));
            String result = new String(Base64.encodeToByte(pasByte), enCoding);
            return result;
        } catch (Exception e) {
            throw new RuntimeSecurityException(e);
        }
    }

    public String decode(String data) {
        try {
            Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            deCipher.init(Cipher.DECRYPT_MODE, key, iv);
            byte[] byteData = Base64.decode(data.getBytes(enCoding));
            byte[] pasByte = deCipher.doFinal(byteData);
            return new String(pasByte, enCoding);
        } catch (Exception e) {
            throw new RuntimeSecurityException(e);
        }
    }
    public static String defDecode(String str){
        DesEncrypt desEncrypt = new DesEncrypt("zc1sdqeq4xz");
        return desEncrypt.decode(str);
    }
    public static String defEncode(String str){
        DesEncrypt desEncrypt = new DesEncrypt("zc1sdqeq4xz");
        return desEncrypt.encode(str);
    }
    
    public static void main(String[] args) {
        //dnem=mskd0=kdicjw+前面的替换成jdbc.properties中需要加密的key  如:jdbc.passworddnem=mskd0=kdicjw+
        System.out.println(new DesEncrypt("jdbc.password").encode("123"));//这个是需要加密的文字
        
//        System.out.println(new DesEncrypt("jdbc.passworddnem=mskd0=kdicjw+").decode("Pb6OFEcSJQMjClE9AD5u6w=="));
    }

}
 

猜你喜欢

转载自blog.csdn.net/qq_37090962/article/details/81171285