欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot 2.x 从yml文件中读取配置自动解密,同时附上DESUtil

程序员文章站 2024-03-14 11:01:58
...

在SpringBoot 2.x 中,我们通过yml文件来进行各种配置,之前我们需要通过编写一个DESUtil来对获取的配置进行解密,但是通过下面的方式可以直接对配置文件进行自动解密

@Configuration
public class EncryptionPropertyConfig {

    @Bean(name="encryptablePropertyResolver")
    public EncryptablePropertyResolver encryptablePropertyResolver() {
        return new EncryptionPropertyResolver();
    }

    class EncryptionPropertyResolver implements EncryptablePropertyResolver {

        private static final String DES = "[email protected]";

        @Override
        public String resolvePropertyValue(String value) {
            if(StringUtils.isBlank(value)) {
                return value;
            }
            // 返回明文
            if(value.startsWith(DES)) {
                return resolveDESValue(value.substring(DES.length()));
            }
            return value;
        }

        private String resolveDESValue(String value) {
            return DESUtil.getDecryptString(value);
        }

    }
}

这样,我们只需要在yml文件中加上[email protected]为前缀,就可以进行自动解密,省去了手动在代码中进行解密的操作了。

同时附上正常的DESUtil的制作方式

public class DESUtil
{
    private static Key key;
    private static String KEY_STR="**************";

    private static final Logger log = LoggerFactory.getLogger(DESUtil.class);

    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) {
            log.error(e.getMessage(),e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 对字符串进行加密,返回BASE64的加密字符串
     * <功能详细描述>
     * @param str
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static String getEncryptString(String str){
        Base64 base64Encoder = new Base64();
        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.encodeToString(encryptStrBytes);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new RuntimeException(e);
        }

    }

    /**
     * 对BASE64加密字符串进行解密
     * <功能详细描述>
     * @param str
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static String getDecryptString(String encryptStr){
        if(encryptStr==null) {
            return null;
        }
        Base64 base64Encoder = new Base64();
        try {
            byte[] strBytes = base64Encoder.decode(encryptStr);
            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) {
            log.error(e.getMessage(),e);
            throw new RuntimeException(e);
        }

    }

    public static String getEncryptString(String str, String keyStr){
        Base64 base64Encoder = new Base64();
        try {
            Key key = getKey(keyStr);
            byte[] strBytes = str.getBytes("UTF-8");
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encryptStrBytes = cipher.doFinal(strBytes);
            return base64Encoder.encodeToString(encryptStrBytes);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new RuntimeException(e);
        }

    }

    public static String getDecryptString(String encryptStr,String keyStr){
        if(encryptStr==null) {
            return null;
        }
        Base64 base64Encoder = new Base64();
        try {
            Key key = getKey(keyStr);
            byte[] strBytes = base64Encoder.decode(encryptStr);
            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) {
            log.error(e.getMessage(),e);
            throw new RuntimeException(e);
        }

    }

    private static Key getKey(String keyStr) throws NoSuchAlgorithmException{
        KeyGenerator generator = KeyGenerator.getInstance("DES");
        SecureRandom secureRandom=SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(keyStr.getBytes());
        generator.init(secureRandom);
        return generator.generateKey();
    }

}