通常情况下,为了提高安全性,我们需要对数据库的认证信息进行加密操作,然后在启动项目的时候,会自动解密来核对信息是否正确。下面介绍在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. 《N诺机试指南》(五)进制转化

    进制转化类题目类型: 代码详解及注释解答:  //进制转化问题 #include <bits/stdc++.h> using namespace std; int main(){ // 1 ...

  2. 手写-- K-means++

    1. K-means++原理 K均值聚类属于启发式方法,不能保证收敛到全局最优,初始中心的选择会直接影响聚类结果.K-means是随机选择样本点作为聚类中心,容易造成算法局部收敛或者需要较多迭代次数, ...

  3. pytorch之 batch_train

    import torch import torch.utils.data as Data torch.manual_seed(1) # reproducible BATCH_SIZE = 5 # BA ...

  4. mongodb搭建带auth的主从

    1:下载mongodb包(mongodb3.4的方法一样,就是mongodb内用户设置到时候不同用户对应不同库,验证时得先创建某个库到用户参考http://ibruce.info/2015/03/03 ...

  5. centos7.5优化系统脚本(虚拟机下)

    #!/usr/bin/bash #安装常用软件,首先必须自行调整好网卡配置文件,保证可以上网,否则,下列优化会失败 yum -y install wget vim lrzsz bash-complet ...

  6. [Pyhton]连接MSSQL实例并执行SQL语句

    运行环境: 服务器端: MSSQL 2014 Server 2012 R2 程序端: Python 3.7.4 MacOS 10.14.6 CentOS Linux release 7.7.1908 ...

  7. css实现文字过长显示省略号的方法

    <div class="title">当对象内文本溢出时显示省略标记</div> 这是一个例子,其实我们只需要显示如下长度: css实现网页中文字过长截取. ...

  8. 十天学会CS之操作系统——进程管理01

    进程管理01 进程的概念 进程是计算机中一个非常重要的概念,在整个计算机发展历史中,操作系统中程序运行机制的演变按顺序大致可以分为: 单道程序:通常是指每一次将一个或者一批程序(一个作业)从磁盘加载进 ...

  9. bootstrap--font-face问题

    在做仿天猫项目时,预期 已经用cdn加载bootstrap,但是不显示文字图标:实际情况: 发现是引用bootstrap的版本导致的.4.0.0版本及以后的css源码中找不到@font-face.可以 ...

  10. git基础教程(三)

    3.github与git同步 3.1 配置公私钥 3.2 github上建立个人仓库 3.3 本地仓库同步到github #将本地仓库与远端仓库建立连接 #用简写名代替后面的远端连接 git remo ...