SpringBoot——》实现属性的加密解密

推荐链接:
    总结——》【Java】
    总结——》【Mysql】
    总结——》【Spring】
    总结——》【SpringBoot】

一、项目代码

1、启动类:SpringBootApplication.java

package com.example.test;

import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;

@org.springframework.boot.autoconfigure.SpringBootApplication
public class SpringBootApplication {
    public static void main(String[] args) {
        ApplicationContext ac = SpringApplication.run(SpringBootApplication.class,args);
    }
}

2、配置文件:application.properties

# 密码加密
des.password=80c656508072974d

3、加解密工具类:DESUtil.java

package com.example.test;


import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;

/**
 * @author xixaoxian
 */
public class DESUtil {

    public static final String KEY_DES = "DES";
    public static final String KEY = "TY5YIGWFMWK3MOW4Y45KRWW382X3U8NI";


    public static String encrypt(String text, String key) {
        try {
            return byte2hex(encrypt(text.getBytes("UTF8"), key.getBytes("UTF8")));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("加密[" + text + "]发生异常:" + e.getMessage(), e);
        }
    }

    public static String decrypt(String text, String key) {
        try {
            return new String(decrypt(hex2byte(text.getBytes("UTF8")), key.getBytes("UTF8")));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("解密[" + text + "]发生异常:" + e.getMessage(), e);
        }
    }


    private static byte[] encrypt(byte[] data, byte[] key) {
        byte[] bytes = null;
        try {
            javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(KEY_DES);
            cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, SecretKeyFactory.getInstance(KEY_DES).generateSecret(new DESKeySpec(key)), new SecureRandom());
            bytes = cipher.doFinal(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bytes;
    }

    private static byte[] decrypt(byte[] data, byte[] key) {
        byte[] bytes = null;
        try {
            javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(KEY_DES);
            cipher.init(javax.crypto.Cipher.DECRYPT_MODE, SecretKeyFactory.getInstance(KEY_DES).generateSecret(new DESKeySpec(key)), new SecureRandom());
            bytes = cipher.doFinal(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bytes;
    }

    public static byte[] hex2byte(byte[] b) {
        if ((b.length % 2) != 0) {
            throw new IllegalArgumentException("长度不是偶数");
        }
        byte[] b2 = new byte[b.length / 2];
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        return b2;
    }

    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs;
    }

    public static void main(String[] args) {
        String msg = "123456";
        String encrypt = DESUtil.encrypt(msg, DESUtil.KEY);
        System.out.println("DES加密:" + encrypt);

        String decrypt = DESUtil.decrypt(encrypt, DESUtil.KEY);
        System.out.println("DES解密:" + decrypt);
    }
}

二、思路

在这里插入图片描述

1、加载属性文件:SpringBootApplication.run()

属性文件的逻辑其实是通过发布事件触发对应的监听器来实现的

在这里插入图片描述

在这里插入图片描述

2、加载属性文件的监听器:ConfigFileApplicationListener

在这里插入图片描述

3、加载属性文件的后置处理器:EnvironmentPostProcessor

在这里插入图片描述

三、解决方案

方案1:通过自定义监听器,在加载属性文件(ConfigFileApplicationListener)的监听器之后,对加密的文件中做解密处理,同时覆盖之前加密的内容
方案2:通过后置处理器后置处理器,对加密的文件中做解密处理,同时覆盖之前加密的内容

方案1、自定义监听器

省略~~~

方案2、自定义后置处理器

1)后置处理器:SafetyEncryptProcessor.java

package com.example.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;

import java.util.HashMap;
import java.util.Map;

public class SafetyEncryptProcessor implements EnvironmentPostProcessor {
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        for (PropertySource<?> propertySource : environment.getPropertySources()) {
            System.out.println("propertySource = " + propertySource);
            if (propertySource instanceof OriginTrackedMapPropertySource) {
                OriginTrackedMapPropertySource source = (OriginTrackedMapPropertySource) propertySource;
                for (String propertyName : source.getPropertyNames()) {
                    if ("des.password".equals(propertyName)) {
                        Map<String, Object> map = new HashMap<>();
                        // 做解密处理
                        String property = (String) source.getProperty(propertyName);
                        String s = DESUtil.decrypt(property, DESUtil.KEY.toString());
                        System.out.println("des.password解密前:" + property);
                        System.out.println("des.password解密后:" + s);
                        map.put(propertyName, s);
                        
                        // 注意要添加到前面,覆盖
                        environment.getPropertySources().addFirst(new MapPropertySource(propertyName, map));
                    }
                }
            }
        }
    }
}

2)文件注册:META-INF/spring.factories

org.springframework.boot.env.EnvironmentPostProcessor=\
com.bobo.util.SafetyEncryptProcessor

在这里插入图片描述

3)启动项目

在这里插入图片描述

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值