通常情况下,为了提高安全性,我们需要对数据库的认证信息进行加密操作,然后在启动项目的时候,会自动解密来核对信息是否正确。下面介绍在SSM和springboot项目中分别是怎样实现的。

无论是使用SSM还是springboot,首先我们需要一个加密工具,这里我采用的是AES 高级加密算法。

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder; /**
* AES 高级加密算法,本项目中用于对数据库的验证信息进行加密
*/
public class AESUtil { private static String key="111"; /**
* 加密
* @param content
* @param strKey
* @return
* @throws Exception
*/
public static byte[] encrypt(String content,String strKey ) throws Exception {
SecretKeySpec skeySpec = getKey(strKey);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(content.getBytes());
return encrypted;
} /**
* 解密
* @param strKey
* @param content
* @return
* @throws Exception
*/
public static String decrypt(byte[] content,String strKey ) throws Exception {
SecretKeySpec skeySpec = getKey(strKey);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(content);
String originalString = new String(original);
return originalString;
} private static SecretKeySpec getKey(String strKey) throws Exception {
byte[] arrBTmp = strKey.getBytes();
byte[] arrB = new byte[]; // 创建一个空的16位字节数组(默认值为0)
for (int i = ; i < arrBTmp.length && i < arrB.length; i++) {
arrB[i] = arrBTmp[i];
} SecretKeySpec skeySpec = new SecretKeySpec(arrB, "AES"); return skeySpec;
} /**
* base 64 encode
* @param bytes 待编码的byte[]
* @return 编码后的base 64 code
*/
public static String base64Encode(byte[] bytes){
return new BASE64Encoder().encode(bytes);
} /**
* base 64 decode
* @param base64Code 待解码的base 64 code
* @return 解码后的byte[]
* @throws Exception
*/
public static byte[] base64Decode(String base64Code) throws Exception{
return base64Code.isEmpty() ? null : new BASE64Decoder().decodeBuffer(base64Code);
} /**
* AES加密为base 64 code
* @param content 待加密的内容
* @param encryptKey 加密密钥
* @return 加密后的base 64 code
* @throws Exception //加密传String类型,返回String类型
*/
public static String aesEncrypt(String content) throws Exception {
return base64Encode(encrypt(content, key)); }
/**
* 将base 64 code AES解密
* @param encryptStr 待解密的base 64 code
* @param decryptKey 解密密钥
* @return 解密后的string //解密传String类型,返回String类型
* @throws Exception
*/
public static String aesDecrypt(String encryptStr) throws Exception {
return encryptStr.isEmpty() ? null : decrypt(base64Decode(encryptStr), key);
} public static void main(String[] args) throws Exception {
String encrypt = aesEncrypt("123456");
System.out.println(encrypt);
// String decrypt = aesDecrypt("+hf8qB4LhS7L7BzBy83bLg==");
// System.out.println(decrypt);
}
}

一、SSM项目对数据库认证信息进行加密

1.首先我们需要自定义一个类,继承 PropertyPlaceholderConfigurer。编写代码,达到启动服务器时判断哪些字段需要解密,并将解密后的值返回出去

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

public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer{
// 需要加密的字段数组 。这里需要和db.properties中一致
private String[] encryptPropNames = { "db.username", "db.password"}; //解密
protected String convertProperty(String propertyName,String propertyValue) {
if(judgeEncryptOrNot(propertyName)) {
try { String realPropertyValue = AESUtil.aesDecrypt(propertyValue);
return realPropertyValue;//返回解密后的值
} catch (Exception e) {
e.printStackTrace();
} }
return propertyValue;
} //判断是否需要加密
public boolean judgeEncryptOrNot(String propertyName) { for(String encryptPropName : encryptPropNames ) {
if(encryptPropName.equals(propertyName)) {
return true;
}
}
return false;
} }



2.此时,我们的db.properties中的信息
就可以填写为我们在AES.util类中数据库认证信息进行加密之后的字符串了。


3.最后,在配置文件中(applicationContext-dao.xml)中定义这个bean即可


二、springboot项目对数据库认证信息进行加密

1.首先我们需要自定义一个类,继承 PropertyPlaceholderConfigurer。编写代码,达到启动服务器时判断哪些字段需要解密,并将解密后的值返回出去

package net.cqwu.collegeo2o.util;

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

//继承该类之后在spring-dao 中引入 可以实现加解密
public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer{
// 需要加密的字段数组 。这里需要和db.properties中一致
private String[] encryptPropNames = { "jdbc.username", "jdbc.password"}; //解密
protected String convertProperty(String propertyName,String propertyValue) {
if(judgeEncryptOrNot(propertyName)) {
try { String realPropertyValue = AESUtil.aesDecrypt(propertyValue);
return realPropertyValue;//返回解密后的值
} catch (Exception e) {
e.printStackTrace();
} }
return propertyValue;
} //判断是否需要加密
public boolean judgeEncryptOrNot(String propertyName) { for(String encryptPropName : encryptPropNames ) {
if(encryptPropName.equals(propertyName)) {
return true;
}
} return false;
} }


2.此时,我们的application.yml或application.properties中的信息
就可以填写为我们在AES.util类中数据库认证信息进行加密之后的字符串了。



3.创建一个类,对应于SSM中的applicationContext-dao.xml

package net.cqwu.collegeo2o.config.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import net.cqwu.collegeo2o.util.AESUtil;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 对应spring 的 application-dao.xml
 */

@Configuration  //表示该配置是需要写入spring的IOC容器中
@MapperScan("net.cqwu.collegeo2o.dao") //指定mapper接口所在的包,进行自动扫描(配置mybatismapper的扫描路径)
public class DataSourceConfiguration {
    //定义数据库的基本信息属性
    @Value("${jdbc.driver}")
    private String jdbcDriver;
    @Value("${jdbc.url}")
    private String jdbcUrl;
    @Value("${jdbc.username}")
    private String jdbcUsername;
    @Value("${jdbc.password}")
    private String jdbcPassword;

//创建一个dataSource对象
    @Bean(name = "dataSource")

public ComboPooledDataSource createDataSourceBean() throws Exception {
        //创建dataSource对象 并设置属性
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(jdbcDriver);
        dataSource.setJdbcUrl(jdbcUrl);
        dataSource.setUser(AESUtil.aesDecrypt(jdbcUsername));  //需要先进行解密工作
        dataSource.setPassword(AESUtil.aesDecrypt(jdbcPassword));
        return dataSource;
    }
}

=========================================================================================================

至此,我们就成功实现了在SSM 和springboot中对数据库认证信息进行加密。

使用SSM 或者 springboot +mybatis时,对数据库的认证信息(用户名,密码)进行加密。的更多相关文章

  1. cxf 调用 webservice服务时传递 服务器验证需要的用户名密码

    cxf通过wsdl2java生成客户端调用webservice时,如果服务器端需要通过用户名和密码验证,则客户端必须传递验证所必须的用户名和密码,刚开始想通过url传递用户名和密码,于是在wsdl文件 ...

  2. springMVC web项目 对访问数据库的用户名密码进行加密解密

    在使用springMVC开发web项目中,数据库的用户名,密码一般都是配置在.properties文件中 然后在通过.xml配置文件引入.properties的变量,例如 在config.proper ...

  3. 通用mapper版+SpringBoot+MyBatis框架+mysql数据库的整合

    转:https://blog.csdn.net/qq_35153200/article/details/79538440 开发环境: 开发工具:Intellij IDEA 2017.2.3 JDK : ...

  4. springboot+mybatis+达梦数据库

    准备工作: 首先,安装达梦6数据库.安装完之后如下建表 然后,很重要的一点(写法一定要这样写,否则无限报错) 达梦数据库查表方式: select  *  from    "库名". ...

  5. 第二篇 Springboot mybatis generate根据数据库表自动生成实体类、Mapper和Mapper.xml

    源码链接:https://pan.baidu.com/s/1iP4UguBufHbcIEv4Ux4wDw 提取码:j6z9 目录结构如下:只需增加一个generatorConfig.xml文件和在po ...

  6. idea中运行ssm 或springboot项目时,project Structure的配置

    ctrl+alt+shift+s进入 project Structure 首先是project选项 Modules 标明source testsource 以及 resource 和 testreso ...

  7. AXIS 调用 webservice服务时传递 服务器验证需要的用户名密码

    System.setProperty("javax.net.ssl.trustStore", T.class.getResource(".").getPath( ...

  8. CSDN数据库下载地址 CSDN 用户名密码泄漏,600万数据下载

    原文发布时间为:2011-12-21 -- 来源于本人的百度文章 [由搬家工具导入] 12月21日消息,下午有网友爆料称国内最大的开发者社区CSDN.NET的安全系统遭到黑客攻击,CSDN数据库中的6 ...

  9. springboot+mybatis集成多数据源MySQL/Oracle/SqlServer

    日常开发中可能时常会遇到一些这样的需求,业务数据库和第三方数据库,两个或多个数据库属于不同数据库厂商,这时候就需要通过配置来实现对数据库实现多源处理.大致说一下我的业务场景,框架本身是配置的sprin ...

随机推荐

  1. 了解EBP指针

    在寄存器里面有很多寄存器虽然他们的功能和使用没有任何的区别,但是在长期的编程和使用中,在程序员习惯中已经默认的给每个寄存器赋上了特殊的含义,比如:EAX一般用来做返回值,ECX用于记数等等.在win3 ...

  2. Codeforces 1296F Berland Beauty

    题目链接:http://codeforces.com/problemset/problem/1296/F 思路: 1————2————3————4————5————6 1->3 2 2-> ...

  3. python笔记18(复习)

    今日内容 复习 内容详细 1.Python入门 1.1 环境的搭建 mac系统上搭建python环境. 环境变量的作用:方便在命令行(终端)执行可执行程序,将可执行程序所在的目录添加到环境变量,那么以 ...

  4. Ubuntu下python使用pyenv+virtualenv进行版本和包隔离

    安装pyenv 参考:https://github.com/pyenv/pyenv git clone https://github.com/pyenv/pyenv.git ~/.pyenv echo ...

  5. HTML5与HTML4的区别-----通用的排版结构

    一个网页通常分为:头部,主体内容和脚部三个部分,当然也有其他更细的划分方法. 以移动端为例, 当给一个设计图,我通常使用一下结构: <div  class="container&quo ...

  6. oracle怎么建立本地连接

    sqlplus连接oracle数据库(连接本地oracle数据库和连接远程的oracle数据库) 虽然我们现在平时都是使用PLSQL Developer这个软件工具了,但是我们还是要了解sqlplus ...

  7. JAVA体系结构简单介绍

    JAVA 体系结构包括四个独立但相关的技术: java程序设计语言 java class 文件格式 JAVA应用编程接口(API) JAVA虚拟机(JVM) 当编写运行一个java程序时,就同时体验了 ...

  8. 洛谷P1179 【数字统计】

    题目传送门 此题题意十分明确:就是让我们统计在[L , R]区间内的数字2出现的次数. 然后我们再看一看此题的数据范围:1≤L≤R≤100000,所以用n log n的复杂度是可以过的. 1.解题思路 ...

  9. PyTorch可视化——tensorboard、visdom

    一.pytorch与tensorboard结合使用 Tensorboard Tensorboard一般都是作为tf的可视化工具,与tf深度集成,它能够展现tf的网络计算图,绘制图像生成的定量指标图以及 ...

  10. C#开源组件DocX版本区别点滴

    在C#中,需要处理Office Word文档时,由于MsOffice Com的版本局限性,所以选择不与本机MsOffice安装与否或安装版本相关的软件,以便软件或使用时的通用性与版权限制,特别是对于国 ...