侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

SSM实现mysql数据库账号密码密文登录功能

数据库  /  管理员 发布于 8年前   340

引言

      咱们公司从事的是信息安全涉密应用的一些项目研发一共有分为三步,相比较于一般公司和一般的项目,对于信息安全要求更加严格,领导要求数据量和用户的用户名及密码信息都必需是要密文配置和存储的,这就涉及到jdbc.properties文件中的数据库的用户名和密码也是一样的,需要配置问密文,在连接的时候再加载解密为明文进行数据库的连接操作,以下就是实现过程,一共有分为三步。

一、创建DESUtil类

提供自定义密钥,加密解密的方法。

package com.hzdy.DCAD.common.util;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import java.security.Key;import java.security.SecureRandom;/** * Created by Wongy on 2019/8/8. */public class DESUtil {  private static Key key;  //自己的密钥  private static String KEY_STR = "mykey";  static {    try {      KeyGenerator generator = KeyGenerator.getInstance("DES");      SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");      secureRandom.setSeed(KEY_STR.getBytes());      generator.init(secureRandom);      key = generator.generateKey();      generator = null;    } catch (Exception e) {      throw new RuntimeException(e);    }  }  /**   * 对字符串进行加密,返回BASE64的加密字符串   *   * @param str   * @return   * @see [类、类#方法、类#成员]   */  public static String getEncryptString(String str) {    BASE64Encoder base64Encoder = new BASE64Encoder();    try {      byte[] strBytes = str.getBytes("UTF-8");      Cipher cipher = Cipher.getInstance("DES");      cipher.init(Cipher.ENCRYPT_MODE, key);      byte[] encryptStrBytes = cipher.doFinal(strBytes);      return base64Encoder.encode(encryptStrBytes);    } catch (Exception e) {      throw new RuntimeException(e);    }  }  /**   * 对BASE64加密字符串进行解密   *   */  public static String getDecryptString(String str) {    BASE64Decoder base64Decoder = new BASE64Decoder();    try {      byte[] strBytes = base64Decoder.decodeBuffer(str);      Cipher cipher = Cipher.getInstance("DES");      cipher.init(Cipher.DECRYPT_MODE, key);      byte[] encryptStrBytes = cipher.doFinal(strBytes);      return new String(encryptStrBytes, "UTF-8");    } catch (Exception e) {      throw new RuntimeException(e);    }  }  public static void main(String[] args) {    String name = "dbuser";    String password = "waction2016";    String encryname = getEncryptString(name);    String encrypassword = getEncryptString(password);    System.out.println("encryname : " + encryname);    System.out.println("encrypassword : " + encrypassword);    System.out.println("name : " + getDecryptString(encryname));    System.out.println("password : " + getDecryptString(encrypassword));  }}

二、 创建EncryptPropertyPlaceholderConfigurer类

建立与配置文件的关联。

package com.hzdy.DCAD.common.util;import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {  //属性需与配置文件的KEY保持一直  private String[] encryptPropNames = {"jdbc.username", "jdbc.password"};  @Override  protected String convertProperty(String propertyName, String propertyValue) {    //如果在加密属性名单中发现该属性     if (isEncryptProp(propertyName)) {      String decryptValue = DESUtil.getDecryptString(propertyValue);      System.out.println(decryptValue);      return decryptValue;    } else {      return propertyValue;    }  }  private boolean isEncryptProp(String propertyName) {    for (String encryptName : encryptPropNames) {      if (encryptName.equals(propertyName)) {        return true;      }    }    return false;  }}

三、 修改配置文件 jdbc.properties

#加密配置之前#jdbc.driver=com.mysql.jdbc.Driver#jdbc.user=root#jdbc.password=root#jdbc.url=jdbc:mysql://localhost:3306/bookstore#加密配置之后jdbc.driver=com.mysql.jdbc.Driverjdbc.user=Ov4j7fKiCzY=jdbc.password=Ov4j7fKiCzY=jdbc.url=jdbc:mysql://localhost:3306/bookstore

四、 修改spring-content.xml配置文件

将spring-context中的 <context:property-placeholder location="classpath:.properties" /> 修改为 <bean class="com.hzdy.DCAD.common.util.EncryptPropertyPlaceholderConfigurer"p:locations="classpath:*.properties"/> //注意只能存在一个读取配置文件的bean,否则系统只会读取最前面的

   注意:如果发现配置密文的username和password可以加载并解密成功,但是最后连接的时候还是以密文连接并报错,这可能涉及到内存预加载的问题,项目一启动,程序会加密密文的用户名和密码,就算最后解密成功了,最后连接数据库读取的却还是密文,这时候我们可以自己重写连接池的方法,让spring-content.xml加载重写的连接池方法,并在连接的时候再提前进行解密。

package com.thinkgem.jeesite.common.encrypt;import java.sql.Connection;import java.sql.SQLException;import java.util.Properties;import javax.security.auth.callback.PasswordCallback;import com.alibaba.druid.util.DruidPasswordCallback;/** */@SuppressWarnings("serial")public class DruidDataSource extends com.alibaba.druid.pool.DruidDataSource {  public PhysicalConnectionInfo createPhysicalConnection() throws SQLException {    String url = this.getUrl();    Properties connectProperties = getConnectProperties();    String user;    if (getUserCallback() != null) {      user = getUserCallback().getName();    } else {      user = getUsername();    }    //DES解密    user = DESUtils.getDecryptString(user);    String password = DESUtils.getDecryptString(getPassword());    PasswordCallback passwordCallback = getPasswordCallback();    if (passwordCallback != null) {      if (passwordCallback instanceof DruidPasswordCallback) {        DruidPasswordCallback druidPasswordCallback = (DruidPasswordCallback) passwordCallback;        druidPasswordCallback.setUrl(url);        druidPasswordCallback.setProperties(connectProperties);      }      char[] chars = passwordCallback.getPassword();      if (chars != null) {        password = new String(chars);      }    }    Properties physicalConnectProperties = new Properties();    if (connectProperties != null) {      physicalConnectProperties.putAll(connectProperties);    }    if (user != null && user.length() != 0) {      physicalConnectProperties.put("user", user);    }    if (password != null && password.length() != 0) {      physicalConnectProperties.put("password", password);    }    Connection conn;    long connectStartNanos = System.nanoTime();    long connectedNanos, initedNanos, validatedNanos;    try {      conn = createPhysicalConnection(url, physicalConnectProperties);      connectedNanos = System.nanoTime();      if (conn == null) {        throw new SQLException("connect error, url " + url + ", driverClass " + this.driverClass);      }      initPhysicalConnection(conn);      initedNanos = System.nanoTime();      validateConnection(conn);      validatedNanos = System.nanoTime();      setCreateError(null);    } catch (SQLException ex) {      setCreateError(ex);      throw ex;    } catch (RuntimeException ex) {      setCreateError(ex);      throw ex;    } catch (Error ex) {      createErrorCount.incrementAndGet();      throw ex;    } finally {      long nano = System.nanoTime() - connectStartNanos;      createTimespan += nano;    }    return new PhysicalConnectionInfo(conn, connectStartNanos, connectedNanos, initedNanos, validatedNanos);  }}

修改spring-content.xml文件的数据库连接数配置

#修改之前<!-- <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> -->#修改之后<bean id="dataSource"class="com.thinkgem.jeesite.common.encrypt.DruidDataSource"     init-method="init" destroy-method="close">    <!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->    <property name="driverClassName" value="${jdbc.driver}" />    <!-- 基本属性 url、user、password -->    <property name="url" value="${jdbc.url}" />    <property name="username" value="${jdbc.username}" />    <property name="password" value="${jdbc.password}" />  </bean>

至此,数据库密文配置连接就完成了!

总结

以上所述是小编给大家介绍的SSM实现mysql数据库账号密码密文登录功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!


  • 上一条:
    MYSQL数据库表结构优化方法详解
    下一条:
    Linux 初始化MySQL 数据库报错解决办法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 分库分表的目的、优缺点及具体实现方式介绍(0个评论)
    • DevDB - 在 VS 代码中直接访问数据库(0个评论)
    • 在ubuntu系统中实现mysql数据存储目录迁移流程步骤(0个评论)
    • 在mysql中使用存储过程批量新增测试数据流程步骤(0个评论)
    • php+mysql数据库批量根据条件快速更新、连表更新sql实现(0个评论)
    • 近期文章
    • 在go语言中实现字符串可逆性压缩及解压缩功能(0个评论)
    • 使用go + gin + jwt + qrcode实现网站生成登录二维码在app中扫码登录功能(0个评论)
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-06
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-01
    • 2018-05
    • 2018-10
    • 2018-11
    • 2020-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2021-02
    • 2021-04
    • 2021-07
    • 2021-08
    • 2021-11
    • 2021-12
    • 2022-02
    • 2022-03
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-07
    • 2023-08
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-03
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客