Spring数据源及配置文件数据加密实现过程详解

The following example shows the corresponding XML configuration:

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="${jdbc.driverClassName}"/>
  <property name="url" value="${jdbc.url}"/>
  <property name="username" value="${jdbc.username}"/>
  <property name="password" value="${jdbc.password}"/>
</bean>

<context:property-placeholder location="jdbc.properties"/>

Spring在第三方依赖包中包含了两个数据源的实现类包,其一是:Apache的DBCP;其二是C3P0,可以在Spring配置文件中利用二者的任何一个配置数据源.

The next two examples show the basic connectivity and configuration for DBCP and C3P0. To learn about more options that help control the pooling features, see the product documentation for the respective connection pooling implementations.

The following example shows DBCP configuration:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
  <property name="driverClassName" value="${jdbc.driverClassName}"/>
  <property name="url" value="${jdbc.url}"/>
  <property name="username" value="${jdbc.username}"/>
  <property name="password" value="${jdbc.password}"/>
</bean>

<context:property-placeholder location="jdbc.properties"/>

The following example shows C3P0 configuration:

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
  <property name="driverClass" value="${jdbc.driverClassName}"/>
  <property name="jdbcUrl" value="${jdbc.url}"/>
  <property name="user" value="${jdbc.username}"/>
  <property name="password" value="${jdbc.password}"/>
</bean>

<context:property-placeholder location="jdbc.properties"/>

在jdbc.properties文件中定义属性的值,如下:

jdbc.driverClassName=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3309/sampledb

jdbc.username=root

jdbc.password=123456

但是这些属性是以明文形式存放,那么任何拥有服务器登录权限的人都可以查看这些机密信息,容易造成数据库访问权限的泄露.

这就要求对应用程序配置文件对某些属性进行加密,让Spring容器在读取属性文件后,在内存中对属性进行解密,然后再将解密后的属性赋给目标对象.

这里提供一个加密解密工具(DES对称加密解密)代码:

package com.springboot.utils;

import java.security.Key;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

public class DESUtils {
  //指定DES加密解密所用的密钥
  private static Key key;
  private static String KEY_STR = "myKey";

  static {
    try {
      KeyGenerator generator = KeyGenerator.getInstance("DES");
      generator.init(new SecureRandom(KEY_STR.getBytes()));
      key = generator.generateKey();
      generator = null;
    }catch(Exception e) {
      throw new RuntimeException(e);
    }
  }

  public static String getEncryptString(String str) {
    Encoder encoder = Base64.getEncoder();
    try {
      byte[] strBytes = str.getBytes("UTF8");
      Cipher cipher = Cipher.getInstance("DES");
      cipher.init(Cipher.ENCRYPT_MODE, key);
      byte[] encryptStrBytes = cipher.doFinal(strBytes);
      return encoder.encodeToString(encryptStrBytes);
    }catch(Exception e) {
      throw new RuntimeException(e);
    }
  }

  public static String getDecryptString(String str) {
    Decoder decoder = Base64.getDecoder();
    try {
      byte[] strBytes = decoder.decode(str);
      Cipher cipher = Cipher.getInstance("DES");
      cipher.init(Cipher.DECRYPT_MODE, key);
      byte[] decryptStrBytes = cipher.doFinal(strBytes);
      return new String(decryptStrBytes,"UTF8");
    }catch(Exception e) {
      throw new RuntimeException(e);
    }
  }

  public static void main(String[] args) throws Exception{
    if(args == null || args.length < 1) {
      System.out.println("请输入要加密的字符,用空格分隔.");
    }else {
      for(String arg : args) {
        System.out.println(arg + ":" + getEncryptString(arg));
      }
    }
  }
}

针对配置文件中加密信息的解密

package com.springboot.utils;

import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

public class EncryptPropertyPlaceholderConfigurer extends PropertySourcesPlaceholderConfigurer{
  private String[] encryptPropNames = {"userName","password"};

  private boolean isEncryptProp(String propertyName) {
    for(String encryptProName : encryptPropNames) {
      if(encryptProName.equals(propertyName)) {
        return true;
      }
    }
    return false;
  }
  @Override
  protected String convertProperty(String propertyName, String propertyValue) {
    if(isEncryptProp(propertyName)) {
      String decryptVal = DESUtils.getDecryptString(propertyValue);
      System.out.println("decryptVal = " + decryptVal);
      return decryptVal;
    }else {
      return propertyValue;
    }
  }
}

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:p="http://www.springframework.org/schema/p"
  xmlns:util="http://www.springframework.org/schema/util"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd
    http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

   <bean class="com.springboot.utils.EncryptPropertyPlaceholderConfigurer"
     p:location="classpath:application.properties"
     p:fileEncoding="utf-8"/>
   <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>

通过在控制台运行我们的加密代码获取加密后的密文

yusuwudeMacBook-Pro:classes yusuwu$ java com.springboot.utils.DESUtils root 123

获取密文:

root:jxlNoW/DjKw=

123:RbtzyNE4tjY=

在application.properties中配置

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/springboot
userName=jxlNoW/DjKw=
password=RbtzyNE4tjY=

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • 解决Springboot2.1.x配置Activiti7单独数据源问题

    1|1简介 最近基于最新的Activiti7配置了SpringBoot2. 简单上手使用了一番.发现市面上解决Activiti7的教程很少,采坑也比较多,在Activiti6配置数据源和Activiti7有所区别,基于Activiti6在Activiti7里是无法正常使用的.接下来让我们看下区别. 1|2问题 Activiti6多数据源配置 6的配置比较简单点. 先加入配置: # activiti 数据源 spring.datasource.activiti.driver=com.mysql.j

  • springboot v2.0.3版本多数据源配置方法

    本篇分享的是springboot多数据源配置,在从springboot v1.5版本升级到v2.0.3时,发现之前写的多数据源的方式不可用了,捕获错误信息如: 异常:jdbcUrl is required with driverClassName. 先来说下之前的多数据源配置如: spring: datasource: url: jdbc:sqlserver://192.168.122.111;DatabaseName=flight username: sa password: 1234.abc

  • spring+Jpa多数据源配置的方法示例

    今天临下班时遇到了一个需求,我的管理平台需要从不同的数据库中获取数据信息,这就需要进行Spring的多数据源配置,对于这种配置,第一次永远都是痛苦的,不过经历了这次的折磨,今后肯定会对这种配置印象深刻.我们这里简单回顾一下流程. 我们配置了两个数据库,一个是公司的数据库,另一个是我本地的一个数据库.首先是application.yml的配置(其中对于公司的数据库我们采取了假的地址,而本机的数据库是真是存在对应的表和库的) 数据库信息: 数据表信息: 1.application.yml datas

  • SpringBoot整合MyBatisPlus配置动态数据源的方法

    MybatisPlus特性 •无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑 •损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作 •强大的 CRUD 操作:内置通用 Mapper.通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求 •支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错 •支持多种数据库:支持 MySQL.MariaDB.Ora

  • Spring Boot+Jpa多数据源配置的完整步骤

    关于 有时候,随着业务的发展,项目关联的数据来源会变得越来越复杂,使用的数据库会比较分散,这个时候就会采用多数据源的方式来获取数据.另外,多数据源也有其他好处,例如分布式数据库的读写分离,集成多种数据库等等. 下面分享我在实际项目中配置多数据源的案例.话不多说了,来一起看看详细的介绍吧 步骤 1.application.yml文件中,配置数据库源.这里primary是主库,secondary是从库. server: port: 8089 # 多数据源配置 #primary spring: pri

  • springboot-mongodb的多数据源配置的方法步骤

    在日常工作中,我们可能需要连接多个MongoDB数据源,比如用户库user,日志库log.本章我们来记录连接多个数据源的步骤,以两个数据源为例,多个数据源类推. 1.pom.xml中引入mongodb的依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </d

  • 通过springboot+mybatis+druid配置动态数据源

    一.建数据库和表 1.数据库demo1放一张user表 SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL, `name` varchar(255) DEFAULT NU

  • Spring数据源及配置文件数据加密实现过程详解

    The following example shows the corresponding XML configuration: <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driverCl

  • Spring基于xml文件配置Bean过程详解

    这篇文章主要介绍了spring基于xml文件配置Bean过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 通过全类名来配置: class:bean的全类名,通过反射的方式在IOC容器中创建Bean,所以要求bean中必须有一个无参的构造器. <bean id="helloWorld" class="com.gong.spring.beans.HelloWorld"> <property na

  • Spring AOP的概念与实现过程详解

    目录 Aop 实现aop方式一 实现aop方式二 注解实现aop Aop 什么是Aop? AOP就是面向切面编程,通过预编译方式以及运行期间的动态代理技术来实现程序的统一维护功能. 什么是切面,我理解的切面就是两个方法之间,两个对象之间,两个模块之间就是一个切面.假设在两个模块之间需要共同执行一系列操作,并且最后将这一系列操作注入到两个模块之间的指定位置.此时这一系列操作就是切面,注入这些操作的位置称之为切点. 举例:公司员工上班 A员工上班需要在前台进行打卡,同样的B员工…其他员工都需要在前台

  • Spring Boot Admin Server管理客户端过程详解

    要通过Spring Boot Admin Server监视和管理微服务应用程序,应该添加Spring Boot Admin启动器客户端依赖项,并将Admin Server URI指向应用程序属性文件. 注 - 要监视应用程序,应为微服务应用程序启用Spring Boot Actuator端点. 首先,在构建配置文件中添加以下Spring Boot Admin启动程序客户端依赖项和Spring Boot启动程序执行程序依赖项. Maven用户可以在pom.xml 文件中添加以下依赖项 - <dep

  • Spring boot项目使用thymeleaf模板过程详解

    在spring boot 项目中使用thymeleaf模板,将后台数据传递给前台界面. 1.将后台数据传递给前台有很多种方式,可以将后台要传递的数据转换成json格式,去传递给前台,也可以通过model形式去传递出去,这篇博客主要是使用thymeleaf模板,将后台数据传递给前台. 2.首先要在spring boot 项目中添加如下依赖: <dependency> <groupId>org.springframework.boot</groupId> <artif

  • Spring Boot整合web层实现过程详解

    Spring Boot中对Spring MVC的文件上传是一脉相传的,我们双击shift去搜CommonsMultipartResolver这个类,它是文件上传的一个实现类.我们先看一下源码: 我们可以看到它是MultipartResolver的实现类,我们再Ctrl+H,就可以看到右侧MultipartResolver的两个实现类.第一个实现类在servlet3.0之后,什么都不用加,就可以直接使用.第二个实现类的兼容性要好一些,早期的servlet也可以使用,但需要自己额外的加依赖.那么在S

  • Spring Boot使用Servlet及Filter过程详解

    在Spring Boot中使用Servlet,根据Servlet注册方式的不同,有两种使用方式.若使用的是Servlet3.0+版本,则两种方式均可使用:若使用的是Servlet2.5版本,则只能使用配置类方式 一.Servlet3.0+版本方式 (1)创建工程07-servlet (2)导入依赖 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apa

  • Spring Boot Async异步执行任务过程详解

    异步调用就是不用等待结果的返回就执行后面的逻辑,同步调用则需要等带结果再执行后面的逻辑. 通常我们使用异步操作都会去创建一个线程执行一段逻辑,然后把这个线程丢到线程池中去执行,代码如下: ExecutorService executorService = Executors.newFixedThreadPool(10); executorService.execute(() -> { try { // 业务逻辑 } catch (Exception e) { e.printStackTrace(

  • Spring Security基于json登录实现过程详解

    主要是重写attemptAuthentication方法 导入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot&l

  • spring Security的自定义用户认证过程详解

    首先我需要在xml文件中声明.我要进行自定义用户的认证类,也就是我要自己从数据库中进行查询 <http pattern="/*.html" security="none"/> <http pattern="/css/**" security="none"/> <http pattern="/img/**" security="none"/> <h

随机推荐