【Spring】使用AES算法加密数据库连接配置并使用密文访问数据库

论坛 期权论坛 脚本     
匿名技术用户   2020-12-22 07:25   28   0

一般我们都会在SSM项目中使用明文方式进行数据库的访问,然而这样做的方式不安全,容易泄露个人的信息

一般的jdbc的配置是这样的:

jdbc.username=root
jdbc.password=123456

我们可以数据库的用户名和密码进行加密,这样就能大大增加系统的安全性
例如:

encrypt.jdbc.username=uKXp9J7+X8lEB0KRJrK5oQ==
encrypt.jdbc.password=N1B3Nleg/d7IbThNCKH0Xw==

那么怎样才能实现呢?
我们可以利用Spring来进行配置

首先我们需要一套加密解密的算法

package Study.Tools;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @date 2018/11/9
 */
public class SecretKit {
    /*
     * 加密
     * 1.构造密钥生成器
     * 2.根据ecnodeRules规则初始化密钥生成器
     * 3.产生密钥
     * 4.创建和初始化密码器
     * 5.内容加密
     * 6.返回字符串
     */
    public static String enc(String encodeRules,String content){
        try {
            //1.构造密钥生成器,指定为AES算法,不区分大小写
            KeyGenerator keygen=KeyGenerator.getInstance("AES");
            //2.根据ecnodeRules规则初始化密钥生成器
            //生成一个128位的随机源,根据传入的字节数组
            keygen.init(128, new SecureRandom(encodeRules.getBytes()));
            //3.产生原始对称密钥
            SecretKey original_key=keygen.generateKey();
            //4.获得原始对称密钥的字节数组
            byte [] raw=original_key.getEncoded();
            //5.根据字节数组生成AES密钥
            SecretKey key=new SecretKeySpec(raw, "AES");
            //6.根据指定算法AES自成密码器
            Cipher cipher=Cipher.getInstance("AES");
            //7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
            cipher.init(Cipher.ENCRYPT_MODE, key);
            //8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
            byte [] byte_encode=content.getBytes("utf-8");
            //9.根据密码器的初始化方式--加密:将数据加密
            byte [] byte_AES=cipher.doFinal(byte_encode);
            //10.将加密后的数据转换为字符串
            //这里用Base64Encoder中会找不到包
            //解决办法:
            //在项目的Build path中先移除JRE System Library,再添加库JRE System Library,重新编译后就一切正常了。
            String AES_encode=new String(new BASE64Encoder().encode(byte_AES));
            //11.将字符串返回
            return AES_encode;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //如果有错就返加nulll
            return null;
    }
    /*
     * 解密
     * 解密过程:
     * 1.同加密1-4步
     * 2.将加密后的字符串反纺成byte[]数组
     * 3.将加密内容解密
     */
    public static String dec(String encodeRules,String content){
        try {
            //1.构造密钥生成器,指定为AES算法,不区分大小写
            KeyGenerator keygen=KeyGenerator.getInstance("AES");
            //2.根据ecnodeRules规则初始化密钥生成器
            //生成一个128位的随机源,根据传入的字节数组
            keygen.init(128, new SecureRandom(encodeRules.getBytes()));
            //3.产生原始对称密钥
            SecretKey original_key=keygen.generateKey();
            //4.获得原始对称密钥的字节数组
            byte [] raw=original_key.getEncoded();
            //5.根据字节数组生成AES密钥
            SecretKey key=new SecretKeySpec(raw, "AES");
            //6.根据指定算法AES自成密码器
            Cipher cipher=Cipher.getInstance("AES");
            //7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作,第二个参数为使用的KEY
            cipher.init(Cipher.DECRYPT_MODE, key);
            //8.将加密并编码后的内容解码成字节数组
            byte [] byte_content= new BASE64Decoder().decodeBuffer(content);
            /*
             * 解密
             */
            byte [] byte_decode=cipher.doFinal(byte_content);
            String AES_decode=new String(byte_decode,"utf-8");
            return AES_decode;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }

        //如果有错就返加nulll
        return null;
    }

    public static void main(String[] args) {
        String rules = "aksdfjalsdfjlkasjdflasdf";
        //加密 规则可以自定义
        System.out.println("-----加密----");
        String enc = enc(rules,"123456");
        System.out.println(enc);
        System.out.println("------解密----");
        //解密
        String dec = dec(rules, "N1B3Nleg/d7IbThNCKH0Xw==");
        System.out.println(dec);


    }
}

我们可以测试一下加密的结果:
加密解密结果
用户米加密解密结果
接下来我们进行将密文配置进去

直接定义一个类DecryptPropertyPlaceholderConfigurer继承PropertyPlaceholderConfigurer类,重写converProperty方法,并编写一个方法判断属性是否需要扫描

public class DecryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer{  
    /** 
     * 重写父类方法,解密指定属性名对应的属性值 
     */  
    @Override  
    protected String convertProperty(String propertyName,String propertyValue){  
     String decValue = propertyValue;
     try {
         if(isEncryptPropertyVal(propertyName)){  
          decValue =  SecretKit.dec(propertyValue);
         }  
     } catch (Exception e) {
   e.printStackTrace();
  }
     
     return decValue;
    }  
    /** 
     * 判断属性值是否需要解密,这里我约定需要解密的属性名用encrypt开头 
     * @param propertyName 
     * @return 
     */  
    private boolean isEncryptPropertyVal(String propertyName){  
        if(propertyName.startsWith("encrypt")){  
            return true;  
        }else{  
            return false;  
        }  
    }  
}

写好类后我们直接去Spring对该类进行配置(注意:需要在数据源项之前引入

<!-- <context:property-placeholder location="classpath:jdbc.properties" /> -->
    <bean class="cn.qblank.Util.DecryptPropertyPlaceholderConfigurer">
     <property name="location" value="classpath:datasource.properties"></property>
    </bean>

移除原本的明文,改用加载现有的密文
最后不要忘记修改连接的配置文件
配置文件

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP