Spring 对属性文件的加密与解密

一般用于配置密码等敏感信息

解密/加密工具类

package com.baobaotao.placeholder;

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 sherry on 15-6-28.
 */
public class DESUtils {
    /*指定加密/解密使用的密匙*/
    private static Key key;
    /*注意:密匙必须是8的倍数*/
    private static String KEY_STR = "myKeykkk";
    static {
        try {
            /*防止Linux下随机生成key*/
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(KEY_STR.getBytes());

            KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
            //keyGenerator.init(new SecureRandom(KEY_STR.getBytes()));
            keyGenerator.init(secureRandom);
            key = keyGenerator.generateKey();
            keyGenerator = null;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    /*对字符串进行DES加密,返回BASE64编码的加密字符串*/
    public static String getEncryptString(String string){
        BASE64Encoder base64Encoder = new BASE64Encoder();
        try {
            byte[] strBytes = string.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[] decryptStrBytes = cipher.doFinal(strBytes);
            return new String(decryptStrBytes,"UTF-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        args = new String[]{"root","123456"};
        String[] result = new String[2];
        if (args == null||args.length<1){
            System.out.println("请输入要加密的字符串,用空格分割");
        }else {
            int i = 0;
            for (String arg:args){
                System.out.println(arg + ":" + getEncryptString(arg));
                result[i++] = getEncryptString(arg);
            }
        }
        for (String temp:result){
            System.out.println(temp+":"+getDecryptString(temp));
        }
    }
}

属性编辑器

package com.baobaotao.placeholder;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

/**
 * Created by sherry on 15-6-28.
 */
public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
    private String[] encryptPropNames = {"username_mysql","password"};

    @Override
    protected String convertProperty(String propertyName, String propertyValue) {
        if (isEncryptProp(propertyName)){
            String decryptValue = DESUtils.getDecryptString(propertyValue);
            System.out.println("解密结果:"+decryptValue);
            return decryptValue;
        }else {
            System.out.println("无需解密:"+propertyValue);
            return propertyValue;
        }
    }

    /*判断是否是需要进行加密的属性*/
    public boolean isEncryptProp(String propertyName){
        for (String encryptpropertyName:encryptPropNames){
            if (encryptpropertyName.equals(propertyName)){
                return true;
            }
        }
        return false;
    }
}

配置使用

    <bean class="com.baobaotao.placeholder.EncryptPropertyPlaceholderConfigurer"
          p:location="classpath:jdbc.properties"
          p:fileEncoding="UTF-8"/>
    <!--配置数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
          p:driverClassName="${driverClassName}"
          p:url="${url}"
          p:username="${username_mysql}"
          p:password="${password}"/>
原文地址:https://www.cnblogs.com/sherrykid/p/4605464.html