• Java开发小技巧(四):配置文件敏感信息处理


    前言

    不知道在上一篇文章中你有没有发现,jdbc.properties中的数据库密码配置是这样写的:

    jdbc.password=5EF28C5A9A0CE86C2D231A526ED5B388
    

    其实这不是真正的密码,而是经过AES加密的。

    AES的Java实现

    AES(高级加密标准)是美国联邦政府采用的一种区块加密标准,其替代原先的
    DES加密算法,成为对称密钥加密中最流行的算法之一。
    AES加密解密的实现就不具体介绍了,这里直接给出源码:

    package com.demo.project.monitor.util;
    
    import javax.crypto.*;
    import javax.crypto.spec.SecretKeySpec;
    import java.io.UnsupportedEncodingException;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.security.SecureRandom;
    
    public class AESEncryption {
        private String password = "Password";
        public AESEncryption(){
        }
        public AESEncryption(String password){
            this.password = password;
        }
    
        /**
         * 加密
         * @param content 加密内容
         * @return
         */
        public String encrypt(String content) {
            try {
                KeyGenerator kgen = KeyGenerator.getInstance("AES");
                kgen.init(128, new SecureRandom(password.getBytes()));
                SecretKey secretKey = kgen.generateKey();
                byte[] enCodeFormat = secretKey.getEncoded();
                SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
                Cipher cipher = Cipher.getInstance("AES");// 创建密码器
                byte[] byteContent = content.getBytes("utf-8");
                cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
                byte[] result = cipher.doFinal(byteContent);
                return parseByte2HexStr(result); // 加密
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IllegalBlockSizeException e) {
                e.printStackTrace();
            } catch (BadPaddingException e) {
                e.printStackTrace();
            }
            return null;
        }
    
        /**解密
         * @param content  解密内容
         * @return
         */
        public String decrypt(String content) {
            try {
                KeyGenerator kgen = KeyGenerator.getInstance("AES");
                kgen.init(128, new SecureRandom(password.getBytes()));
                SecretKey secretKey = kgen.generateKey();
                byte[] enCodeFormat = secretKey.getEncoded();
                SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
                Cipher cipher = Cipher.getInstance("AES");// 创建密码器
                cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
                byte[] result = cipher.doFinal(parseHexStr2Byte(content));
                return new String(result); // 解密
            } 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();
            }
            return null;
        }
    
        /**
         * 将二进制转换成16进制
         * @param buf
         * @return
         */
        private String parseByte2HexStr(byte buf[]) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < buf.length; i++) {
                String hex = Integer.toHexString(buf[i] & 0xFF);
                if (hex.length() == 1) {
                    hex = '0' + hex;
                }
                sb.append(hex.toUpperCase());
            }
            return sb.toString();
        }
    
        /**
         * 将16进制转换为二进制
         * @param hexStr
         * @return
         */
        private byte[] parseHexStr2Byte(String hexStr) {
            if (hexStr.length() < 1)
                return null;
            byte[] result = new byte[hexStr.length()/2];
            for (int i = 0;i< hexStr.length()/2; i++) {
                int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
                int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
                result[i] = (byte) (high * 16 + low);
            }
            return result;
        }
    }
    

    解密配置文件

    既然配置文件部分内容已经进行了加密处理,那我们在填充上下文的占位符时就要对其进行解密,获得真正的密码,还记得之前我们在加载配置文件的时候使用的类PropertyPlaceholderConfigurer吗?我们可以通过对它的resolvePlaceholder方法进行重写来实现。

    实现过程

    首先创建一个继承自PropertyPlaceholderConfigurer的类EncryptPropertyPlaceholderConfigurer,然后重写它的方法:

    package com.demo.project.monitor.util;
    
    import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
    
    import java.util.Properties;
    
    /**
     * 解密配置文件敏感内容
     */
    public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
        @Override
        protected String resolvePlaceholder(String placeholder, Properties props) {
            String result = props.getProperty(placeholder);
            if(placeholder.endsWith("jdbc.password")){
                AESEncryption aes = new AESEncryption();
                String decrypt = aes.decrypt(result);
                result = decrypt == null ? result : decrypt;
            }
            return result;
        }
    }
    

    接着在spring上下文中将原来的beanorg.springframework.beans.factory.config.PropertyPlaceholderConfigurer修改为我们创建的类即可:

    <bean class="com.demo.project.monitor.util.EncryptPropertyPlaceholderConfigurer">
        <property name="locations">
            <value>classpath:jdbc.properties</value>
        </property>
        <property name="ignoreResourceNotFound" value="false"/>
    </bean>
    

    这样spring在填充占位符的时候就会进行判断,对加密后的敏感信息进行解密处理,得到真实的内容。

    文章项目源码已发布到Github:https://github.com/ZKHDEV/MultDependPjo

    本文为作者kMacro原创,转载请注明来源:http://www.jianshu.com/p/600a4e23c14e。

  • 相关阅读:
    论文翻译:2020_DARCN_A Recursive Network with Dynamic Attention for Monaural Speech Enhancement
    论文翻译:2020_demucs_Real Time Speech Enhancement in the Waveform Domain
    论文翻译:2021_A Perceptually Motivated Approach for Lowcomplexity, Realtime Enhancement of Fullband Speech
    tomcat架构分析及配置详解
    深入了解SpringMVC源码解析
    Spring MVC高级应用
    Nginx应用场景配置
    SpringSecurity基础场景应用大全
    SpringBoot基础应用
    Spring MVC应用
  • 原文地址:https://www.cnblogs.com/zkh101/p/8085709.html
Copyright © 2020-2023  润新知