欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

spring*.xml配置文件明文加密的实现

程序员文章站 2022-06-24 18:11:05
说明:客户要求spring*.xml中oracle/redis/mongodb的ip、端口、用户名、密码不能明文存放,接到需求的我,很无奈,但是还是的硬着头皮搞系统架构:spring+mvc(orac...

说明:客户要求spring*.xml中oracle/redis/mongodb的ip、端口、用户名、密码不能明文存放,接到需求的我,很无奈,但是还是的硬着头皮搞

系统架构:spring+mvc(oracle是用jdbc自己封装的接口)

1.数据库配置文件加密

原xml配置

<?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:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemalocation="
 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
 default-autowire="bytype">
  
<context:component-scan base-package="cn.geoff" use-default-filters="false">
 <context:include-filter type="annotation" expression="org.springframework.stereotype.service"/>
 </context:component-scan>

 <!-- database connection pool -->
 <bean id="datasource" class="com.alibaba.druid.pool.druiddatasource" init-method="init" destroy-method="close">
 <property name="url" value="jdbc:oracle:thin:@192.168.100.100:1521:orcl"/>
 <property name="username" value="geoff"/>
 <property name="password" value="123456"/>
 <property name="validationquery" value="select 'x' from dual"/>

 .....
 </bean>

 <bean id="transactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager">
 <property name="datasource" ref="datasource"/>
 </bean>
  
  </beans>

加密实现过程

思路:继承druiddatasource,在初始化set值的时候进行解密

/**
 * 数据库连接解密
 * @author: geoff
 * @create: 2020-12-30 16:46
 **/
public class databasexml extends druiddatasource {


  /**
   * log4j logger
   */
  private final static logger lg = loggerfactory.getlogger(databasexml.class);

  @override
  public string geturl() {
    return this.jdbcurl;
  }

  @override
  public void seturl(string jdbcurl) {
    if(geoff.data_base_is_encryption) {
      lg.info("数据库【jdbcurl】解密初始化加载...");
      try {
        jdbcurl = encryption.decrypt(jdbcurl, geoff.data_base_encryption_key);
      } catch (exception e) {
        lg.error("数据库【jdbcurl】密文解密失败...");
        e.printstacktrace();
      }
    }
    this.jdbcurl = jdbcurl;
  }

  @override
  public string getusername() {
    return this.username;
  }

  @override
  public void setusername(string username) {
    if(geoff.data_base_is_encryption) {
      lg.info("数据库【username】解密初始化加载...");
      try {
        username = encryption.decrypt(username, geoff.data_base_encryption_key);
      } catch (exception e) {
        lg.error("数据库【username】密文解密失败...");
        e.printstacktrace();
      }
    }
    this.username = username;
  }

  @override
  public string getpassword() {
    return this.password;
  }

  @override
  public void setpassword(string password) {
    if(geoff.data_base_is_encryption){
      lg.info("数据库【password】解密初始化加载...");
      try {
        password = encryption.decrypt(password, geoff.data_base_encryption_key);
      } catch (exception e) {
        lg.error("数据库【password】密文解密失败...");
        e.printstacktrace();
      }
    }
    this.password = password;
  }



}

修改后配置文件

<?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:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemalocation="
 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
 default-autowire="bytype">
  
<context:component-scan base-package="cn.geoff" use-default-filters="false">
 <context:include-filter type="annotation" expression="org.springframework.stereotype.service"/>
 </context:component-scan>

 <bean id="datasource" class="cn.geoff.framework.core.databasexml" init-method="init" destroy-method="close">
 <property name="url" value="4lz4l804zidqoj5wt3vnvlzvslsdqcuqwhg5cabq1vg/vx+x+pejq6vjmlpo+pkk"/>
 <property name="username" value="pfez8v4uvb06khqxclvlna=="/>
 <property name="password" value="mmckyd6c5fo="/>
 <property name="validationquery" value="select 'x' from dual"/>

 
 .....
 </bean>

 <bean id="transactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager">
 <property name="datasource" ref="datasource"/>
 </bean>
  
  </beans>

2.redis配置文件加密

原配置文件

<?xml version="1.0" encoding="utf-8"?>
<!doctype beans public "-//spring//dtd bean 2.0//en" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<!-- jedis -->
<beans default-autowire="byname">

 <!-- default pool config -->
 <bean id="defaultjedispoolconfig" class="redis.clients.jedis.jedispoolconfig">
 <property name="maxtotal" value="5"/>
 <property name="maxidle" value="2"/>
 <property name="minidle" value="2"/>
 <property name="testonborrow" value="true"/>
 <property name="testonreturn" value="true"/>
 <property name="testwhileidle" value="true"/>
 </bean>


 <bean id="one" class="redis.clients.jedis.jedispool" destroy-method="destroy">
    <constructor-arg index="0" ref="defaultjedispoolconfig"/>
    <constructor-arg index="1" value="127.0.0.1" type="java.lang.string"/>
    <constructor-arg index="2" value="6379" type="int"/>
    <constructor-arg index="3" value="0" type="int"/>
    <constructor-arg index="4" value="123456" type="java.lang.string"/>
 </bean>


 <bean id="two" class="redis.clients.jedis.jedispool" destroy-method="destroy">
    <constructor-arg index="0" ref="defaultjedispoolconfig"/>
    <constructor-arg index="1" value="127.0.0.1" type="java.lang.string"/>
    <constructor-arg index="2" value="6379" type="int"/>
    <constructor-arg index="3" value="0" type="int"/>
    <constructor-arg index="4" value="123456" type="java.lang.string"/>
 </bean>


 <bean id="three" class="redis.clients.jedis.jedispool" destroy-method="destroy">
    <constructor-arg index="0" ref="defaultjedispoolconfig"/>
    <constructor-arg index="1" value="127.0.0.1" type="java.lang.string"/>
    <constructor-arg index="2" value="6379" type="int"/>
    <constructor-arg index="3" value="0" type="int"/>
    <constructor-arg index="4" value="123456" type="java.lang.string"/>
 </bean>
</beans>

加密实现思路:由于jedispool使用构造函数来创建,所以继承jedispool后,在调用jedispool构造函数的时候,调用static解密方法进行解密

import org.apache.commons.pool2.impl.genericobjectpoolconfig;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import redis.clients.jedis.*;

/**
 * redis数据库用户名密码解密
 * @author: geoff
 * @create: 2020-12-30 17:20
 **/
public class jedispoolxml extends jedispool{


  /**
   * log4j logger
   */
  private final static logger lg = loggerfactory.getlogger(jedispoolxml.class);



  public jedispoolxml(genericobjectpoolconfig poolconfig, string host, string port, string timeout, string password) {
    super(poolconfig,decrypthost(host),decryptport(port),decrypttimeout(timeout),decryptpassword(password), 0, (string)null);
  }

  private jedispoolxml(genericobjectpoolconfig poolconfig, string host, string port,string timeout, string password, string database){
    super(poolconfig,decrypthost(host),decryptport(port),decrypttimeout(timeout),decryptpassword(password),decryptdatabase(database));
  }


  private static string decrypthost(string host){
    if(geoff.data_base_is_encryption) {
      lg.info("redis【host】解密初始化加载...");
      try {
        host = encryption.decrypt(host, geoff.data_base_encryption_key);
      } catch (exception e) {
        lg.error("redis【host】密文解密失败...");
        e.printstacktrace();
      }
    }
    return host;
  }

  private static int decryptport(string port){
    if(geoff.data_base_is_encryption) {
      lg.info("redis【port】解密初始化加载...");
      try {
        port = encryption.decrypt(port, geoff.data_base_encryption_key);
      } catch (exception e) {
        lg.error("redis【port】密文解密失败...");
        e.printstacktrace();
      }
    }
    return integer.parseint(port);
  }

  private static int decrypttimeout(string timeout){
    if(geoff.data_base_is_encryption) {
      lg.info("redis【timeout】解密初始化加载...");
      try {
        timeout = encryption.decrypt(timeout, geoff.data_base_encryption_key);
      } catch (exception e) {
        lg.error("redis【timeout】密文解密失败...");
        e.printstacktrace();
      }
    }
    return integer.parseint(timeout);
  }

  private static string decryptpassword(string password){
    if(geoff.data_base_is_encryption) {
      lg.info("redis【password】解密初始化加载...");
      try {
        password = encryption.decrypt(password, geoff.data_base_encryption_key);
      } catch (exception e) {
        lg.error("redis【password】密文解密失败...");
        e.printstacktrace();
      }
    }
    return password;
  }

  private static int decryptdatabase(string database){
    if(geoff.data_base_is_encryption) {
      lg.info("redis【database】解密初始化加载...");
      try {
        database = encryption.decrypt(database, geoff.data_base_encryption_key);
      } catch (exception e) {
        lg.error("redis【database】密文解密失败...");
        e.printstacktrace();
      }
    }
    return integer.parseint(database);
  }

}

修改后xml

<?xml version="1.0" encoding="utf-8"?>
<!doctype beans public "-//spring//dtd bean 2.0//en" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<!-- jedis -->
<beans default-autowire="byname">

 <bean id="defaultjedispoolconfig" class="redis.clients.jedis.jedispoolconfig">
 <property name="maxtotal" value="5"/>
 <property name="maxidle" value="2"/>
 <property name="minidle" value="2"/>
 <property name="testonborrow" value="true"/>
 <property name="testonreturn" value="true"/>
 <property name="testwhileidle" value="true"/>
 </bean>


 <bean id="one" class="cn.geoff.framework.core.jedispoolxml" destroy-method="destroy">
 <constructor-arg index="0" ref="defaultjedispoolconfig"/>
 <constructor-arg index="1" value="n98/m6a3acrnymqiqexgeg==" type="java.lang.string"/>
 <constructor-arg index="2" value="indccyogs/y=" type="java.lang.string"/>
 <constructor-arg index="3" value="cxszbzysxwy=" type="java.lang.string"/>
 <constructor-arg index="4" value="mmckyd6c5fo=" type="java.lang.string"/>
 </bean>


 <bean id="two" class="cn.geoff.framework.core.jedispoolxml" destroy-method="destroy">
 <constructor-arg index="0" ref="defaultjedispoolconfig"/>
 <constructor-arg index="1" value="n98/m6a3acrnymqiqexgeg==" type="java.lang.string"/>
 <constructor-arg index="2" value="indccyogs/y=" type="java.lang.string"/>
 <constructor-arg index="3" value="cxszbzysxwy=" type="java.lang.string"/>
 <constructor-arg index="4" value="mmckyd6c5fo=" type="java.lang.string"/>
 </bean>


 <bean id="three" class="cn.geoff.framework.core.jedispoolxml" destroy-method="destroy">
 <constructor-arg index="0" ref="defaultjedispoolconfig"/>
 <constructor-arg index="1" value="n98/m6a3acrnymqiqexgeg==" type="java.lang.string"/>
 <constructor-arg index="2" value="indccyogs/y=" type="java.lang.string"/>
 <constructor-arg index="3" value="cxszbzysxwy=" type="java.lang.string"/>
 <constructor-arg index="4" value="mmckyd6c5fo=" type="java.lang.string"/>
 </bean>

</beans>

3.mongodb配置文件加密(使用的是spring-data-mognodb框架)

原xml配置

<?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:mongo="http://www.springframework.org/schema/data/mongo"
 xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">


 <mongo:mongo-client id="mongoclient" host="192.168.100.100" port="27017" credentials="jyzq_zsc:123456@jyzq_zsc">
 
 </mongo:mongo-client>

 <!-- factory -->
 <mongo:db-factory id="mongodbfactory" dbname="pfez8v4uvb06khqxclvlna==" mongo-ref="mongoclient"/>
 <mongo:db-factory id="mongodbfactory" dbname="jyzq_zsc" mongo-ref="mongoclient"/>
 <mongo:mapping-converter id="converter" db-factory-ref="mongodbfactory"/>


 <!-- grid fs template -->
 <bean id="gridfstemplate" class="org.springframework.data.mongodb.gridfs.gridfstemplate">
 <constructor-arg ref="mongodbfactory"/>
 <constructor-arg ref="converter"/>
 </bean>


 <!-- mongo template -->
 <bean id="documenttemplate" class="org.springframework.data.mongodb.core.mongotemplate">
 <constructor-arg ref="mongodbfactory"/>
 <constructor-arg ref="converter"/>
 </bean>

</beans>

加密思路:由于项目使用的时候是获取bean的方式来获取mongotemplate和mongodbfactory的,尝试过各种方法来继承后加密,但是最后都不行,后面只能通过手动的方法进行初始化,并将对应mongotemplate和mongodbfactory注入到bean中

import com.mongodb.*;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.context.annotation.bean;

import org.springframework.context.annotation.configuration;
import org.springframework.data.mongodb.core.mongotemplate;
import org.springframework.data.mongodb.core.simplemongodbfactory;
import org.springframework.data.mongodb.core.convert.defaultdbrefresolver;
import org.springframework.data.mongodb.core.convert.mappingmongoconverter;
import org.springframework.data.mongodb.core.mapping.mongomappingcontext;
import org.springframework.data.mongodb.gridfs.gridfstemplate;

import java.util.arraylist;
import java.util.list;

/**
 * @author: geoff
 * @create: 2020-12-31 16:15
 **/

@configuration
public class mongodbxml {

  /**
   * log4j logger
   */
  private final static logger lg = loggerfactory.getlogger(mongodbxml.class);

  private string host;
  private integer port;
  private string username;
  private string password;
  private string database;

  private simplemongodbfactory mongodbfactory = null;
  private mappingmongoconverter converter = null;


  public string gethost() {
    return host;
  }


  public void sethost(string host) {
    this.host = decrypthost(host);
  }

  public integer getport() {
    return port;
  }


  public void setport(string port) {
    this.port = decryptport(port);
  }

  public string getusername() {
    return username;
  }

  public void setusername(string username) {
    this.username = decryptusername(username);
  }

  public string getpassword() {
    return password;
  }

  public void setpassword(string password) {
    this.password = decryptpassword(password);
  }

  public string getdatabase() {
    return database;
  }

  public void setdatabase(string database) {
    this.database = decryptdatabase(database);
  }

  private string decrypthost(string host){
    if(geoff.data_base_is_encryption) {
      lg.info("mongodb【host】解密初始化加载...");
      try {
        host = encryption.decrypt(host, geoff.data_base_encryption_key);
      } catch (exception e) {
        lg.error("mongodb【host】密文解密失败...");
        e.printstacktrace();
      }
    }
    return host;
  }

  private int decryptport(string port){
    if(geoff.data_base_is_encryption) {
      lg.info("mongodb【port】解密初始化加载...");
      try {
        port = encryption.decrypt(port, geoff.data_base_encryption_key);
      } catch (exception e) {
        lg.error("mongodb【port】密文解密失败...");
        e.printstacktrace();
      }
    }
    return integer.parseint(port);
  }

  private string decryptusername(string username){
    if(geoff.data_base_is_encryption) {
      lg.info("mongodb【username】解密初始化加载...");
      try {
        username = encryption.decrypt(username, geoff.data_base_encryption_key);
      } catch (exception e) {
        lg.error("mongodb【username】密文解密失败...");
        e.printstacktrace();
      }
    }
    return username;
  }

  private string decryptpassword(string password){
    if(geoff.data_base_is_encryption) {
      lg.info("mongodb【password】解密初始化加载...");
      try {
        password = encryption.decrypt(password, geoff.data_base_encryption_key);
      } catch (exception e) {
        lg.error("mongodb【password】密文解密失败...");
        e.printstacktrace();
      }
    }
    return password;
  }

  private string decryptdatabase(string database){
    if(geoff.data_base_is_encryption) {
      lg.info("mongodb【database】解密初始化加载...");
      try {
        database = encryption.decrypt(database, geoff.data_base_encryption_key);
      } catch (exception e) {
        lg.error("mongodb【database】密文解密失败...");
        e.printstacktrace();
      }
    }
    return database;
  }




  public void init() {
    mongoclientoptions.builder build = new mongoclientoptions.builder();
    mongoclientoptions options = build.build();
    try {
      list<serveraddress> addrs = new arraylist<serveraddress>();
      serveraddress serveraddress = new serveraddress(host, port);
      addrs.add(serveraddress);
      mongocredential credential = mongocredential.createscramsha1credential(username, database, password.tochararray());
      list<mongocredential> credentials = new arraylist<mongocredential>();
      credentials.add(credential);
      mongoclient mongoclient = new mongoclient(addrs, credentials, options);
      mongodbfactory = new simplemongodbfactory(mongoclient, database);
      defaultdbrefresolver dbrefresolver = new defaultdbrefresolver(mongodbfactory);
      mongomappingcontext mongomappingcontext = new mongomappingcontext();
      converter = new mappingmongoconverter(dbrefresolver, mongomappingcontext);
      lg.info(" mongodb客户端创建成功 ");
    } catch (exception e) {
      lg.info(" mongodb客户端创建失败 ");
      e.printstacktrace();
    }
    documenttemplate();
    gridfstemplate();


  }

  @bean
  public mongotemplate documenttemplate() {
    if (mongodbfactory != null && converter != null) {
      lg.info("mongotemplate初始化成功......");
      mongotemplate mongotemplate = new mongotemplate(mongodbfactory, converter);
      return mongotemplate;
    } else {
      lg.error("mongotemplate初始化失败......");
      return null;
    }
  }

  @bean
  public gridfstemplate gridfstemplate() {
    if (mongodbfactory != null && converter != null) {
      lg.info("gridfstemplate初始化成功......");
      gridfstemplate gridfstemplate = new gridfstemplate(mongodbfactory, converter);
      return gridfstemplate;
    } else {
      lg.error("gridfstemplate初始化失败......");
      return null;
    }
  }

  public void destroy(){
    try {
      this.mongodbfactory.destroy();
    } catch (exception e) {
      e.printstacktrace();
    }
  }


}

修改后配置文件

<?xml version="1.0" encoding="utf-8"?>
<!doctype beans public "-//spring//dtd bean 2.0//en" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<!-- mongodb -->
<beans>

 <bean id="mongodbxml" class="cn.geoff.framework.core.mongodbxml" init-method="init" destroy-method="destroy" >
 <property name="host" value="ppmnmr+x2uivhg8gmnffqg=="/>
 <property name="port" value="51qh8fifl1k="/>
 <property name="username" value="yre5dufk9os6khqxclvlna=="/>
 <property name="password" value="mmckyd6c5fo="/>
 <property name="database" value="pfez8v4uvb06khqxclvlna=="/>
 </bean>

</beans>

4.最后附上对应的加解密类

import org.apache.commons.codec.binary.base64;

import javax.crypto.cipher;
import javax.crypto.secretkey;
import javax.crypto.secretkeyfactory;
import javax.crypto.spec.deskeyspec;
import java.security.key;
import java.security.securerandom;

/**
 * 加密生成token的方法
 *
 * @author: geoff
 * @create: 2020-12-30 17:03
 **/

public class encryption {
  // 算法名称
  public static final string key_algorithm = "des";
  // 算法名称/加密模式/填充方式
  // des共有四种工作模式-->>ecb:电子密码本模式、cbc:加密分组链接模式、cfb:加密反馈模式、ofb:输出反馈模式
  public static final string cipher_algorithm = "des/ecb/pkcs5padding";

  /**
   * 生成密钥key对象
   *
   * @param
   * @return 密钥对象
   * @throws exception
   */
  private static secretkey keygenerator(string keystr) throws exception {
    byte[] input = hexstring2bytes(keystr);
    deskeyspec deskey = new deskeyspec(input);
    // 创建一个密匙工厂,然后用它把deskeyspec转换成
    secretkeyfactory keyfactory = secretkeyfactory.getinstance(key_algorithm);
    secretkey securekey = keyfactory.generatesecret(deskey);
    return securekey;
  }


  /**
   * 从十六进制字符串到字节数组转换
   */
  public static byte[] hexstring2bytes(string hexstr) {
    byte[] keybytes = hexstr.getbytes();
    if (keybytes.length == 16) {
      byte[] tmpkey = new byte[24];
      system.arraycopy(keybytes, 0, tmpkey, 0, 16);
      system.arraycopy(keybytes, 0, tmpkey, 16, 8);
      keybytes = tmpkey;
    }
    return keybytes;
  }

  /**
   * 加密数据
   *
   * @param data 待加密数据
   * @param key 密钥
   * @return 加密后的数据
   */
  public static string encrypt(string data, string key) throws exception {
    key deskey = keygenerator(key);
    // 实例化cipher对象,它用于完成实际的加密操作
    cipher cipher = cipher.getinstance(cipher_algorithm);
    securerandom random = new securerandom();
    // 初始化cipher对象,设置为加密模式
    cipher.init(cipher.encrypt_mode, deskey, random);
    byte[] results = cipher.dofinal(data.getbytes());
    // 执行加密操作。加密后的结果通常都会用base64编码进行传输
    return base64.encodebase64string(results);
  }

  /**
   * 解密数据
   *
   * @param data 待解密数据
   * @param key 密钥
   * @return 解密后的数据
   */
  public static string decrypt(string data, string key) throws exception {
    key deskey = keygenerator(key);
    cipher cipher = cipher.getinstance(cipher_algorithm);
    // 初始化cipher对象,设置为解密模式
    cipher.init(cipher.decrypt_mode, deskey);
    // 执行解密操作
    return new string(cipher.dofinal(base64.decodebase64(data)));
  }

}

到此这篇关于spring*.xml配置文件明文加密的实现的文章就介绍到这了,更多相关spring*.xml配置文件加密内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!