Spring对属性文件加密解密应用详解

前言
在Spring的开发中,我们在很多情况下会使用占位符引用属性文件的属性值来简化我们的系统及使我们的系统具有更高的灵活性和通用性。这种配置方式有两个明显的好处:
1、减少维护的工作量:资源的配置信息可以多应用共享,在多个应用使用同一资源的情况下,如果资源的地址、用户名等配置信息发生了更改,你只要调整属性文件就可以了;
2、使部署更简单:Spring配置文件主要描述应用程序中的Bean,这些配置信息在开发完成后,应该就固定下来了,在部署应用时,需要根据部署环境调整是就是数据源,邮件服务器的配置信息,将它们的配置信息独立到属性文件中,应用部署人员只需要调整资源属性文件即可,根本不需要关注内容复杂的Spring 配置文件。不仅给部署和维护带来了方便,也降低了出错的机率。

    Spring为我们提供了一个BeanFactoryPostProcessorBean工厂后置处理器接口的实现类:org.springframework.beans.factory.config.PropertyPlaceholderConfigurer,它的主要功能是对引用了外部属性值的<bean>进行处理,将其翻译成真实的配置值。

    一般的属性信息以明文的方式存放在属性文件中并没有什么问题,但如果是数据源或邮件服务器用户名密码等重要的信息,在某些场合,我们可能需要以密文的方式保存。虽然Web应用的客户端用户看不到配置文件的,但有时,我们只希望特定的维护人员掌握重要资源的配置信息,而不是毫无保留地对所有可以进入部署机器的用户开放。
    对于这种具有高度安全性要求的系统(如电信、银行、重点人口库等),我们需要对资源连接等属性配置文件中的配置信息加密存放。然后让Spring容器启动时,读入配置文件后,先进行解密,然后再进行占位符的替换。
    很可惜,PropertyPlaceholderConfigurer只支持明文的属性文件。但是,我们可以充分利用Spring框架的扩展性,通过扩展 PropertyPlaceholderConfigurer类来达到我们的要求。本文将讲解使用加密属性文件的原理并提供具体的实现。

    以传统的方式使用属性文件
    一般情况下,外部属性文件用于定义诸如数据源或邮件服务器之类的配置信息。这里,我们通过一个简单的例子,讲解使用属性文件的方法。假设有一个 car.properties属性文件,文件内容如下:
    brand=红旗CA72
    maxSpeed=250
    price=20000.00
    该文件放在类路径的com/baobaotao/目录下,在Spring配置文件中利用PropertyPlaceholderConfigurer引入这个配置文件,并通过占位符引用属性文件内的属性项,如代码清单 1所示:
代码清单 1 使用外部属性文件进行配置

Xml代码 复制代码
  1. <!-- ① 引入外部属性文件 -->  
  2. <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  3.     <property name="locations">  
  4.        <list>  
  5.           <value>classpath:com/baobaotao/car.properties</value> ② 指定属性文件地址   
  6.        </list>  
  7.     </property>  
  8.     <property name="fileEncoding" value="utf-8"/>  
  9. </bean>  
  10. <!-- ③ 引用外部属性的值,对car进行配置 -->  
  11. <bean id="car" class="com.baobaotao.place.Car">  
  12.     <property name="brand" value="${brand}" />  
  13.     <property name="maxSpeed" value="${maxSpeed}" />  
  14.     <property name="price" value="${price}" />  
  15. </bean>  

    在①处,我们通过PropertyPlaceholderConfigurer这个BeanFactoryPostProcessor实现类引用外部的属性文件,通过它的locations属性指定Spring配置文件中引用到的属性文件,在PropertyPlaceholderConfigurer内部,locations是一个Resource数组,所以你可以在地址前添加资源类型前缀,如②处所示。如果需要引用多个属性文件,只需要在②处添加相应<value>配置项即可。

    分析PropertyPlaceholderConfigurer结构
    我们知道Spring通过PropertyPlaceholderConfigurer提供对外部属性文件的支持,为了使用加密的属性文件,我们就需要分析该类的工作机理,再进行改造。所以我们先来了解一下该类的结构(见附件1)。
    其中PropertiesLoaderSupport类有一个重要的protected void loadProperties(Properties props)方法,查看它的注释,可以知道该方法的作用是将PropertyPlaceholderConfigurer 中locations属性所定义的属性文件的内容读取到props入参对象中。这个方法比较怪,Java很少通过入参承载返回值,但这个方法就是这样。

    所以,我们只要简单地重载这个方法,在将资源文件的内容转换为Properties之前,添加一个解密的步骤就可以了。但是,PropertiesLoaderSupport的设计有一个很让人遗憾的地方,它的locations属性是private的,只提供setter 没有提供getter。因此,无法在子类中获取PropertiesLoaderSupport中的locations(资源地址),所以我们得在子类重新定义locations属性并覆盖PropertiesLoaderSupport中的setLocations()方法。

 

编写支持加密属性文件的实现类
    通过以上分析,我们设计一个支持加密属性文件的增强型PropertyPlaceholderConfigurer,其代码如所示:
代码清单 2

Java代码 复制代码
  1. import java.io.IOException;   
  2. import java.io.InputStream;   
  3. import java.io.InputStreamReader;   
  4. import java.security.Key;   
  5. import java.util.Properties;   
  6. import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;   
  7. import org.springframework.core.io.Resource;   
  8. import org.springframework.util.DefaultPropertiesPersister;   
  9. import org.springframework.util.PropertiesPersister;   
  10. public class DecryptPropertyPlaceholderConfigurer   
  11.         extends PropertyPlaceholderConfigurer ...{   
  12.     private Resource[] locations;   //① 重新定义父类中的这个同名属性   
  13.     private Resource keyLocation; //② 用于指定密钥文件   
  14.     public void setKeyLocation(Resource keyLocation) ...{   
  15.         this.keyLocation = keyLocation;   
  16.     }   
  17.     public void setLocations(Resource[] locations) ...{   
  18.         this.locations = locations;   
  19.     }   
  20.     public void loadProperties(Properties props) throws IOException ...{   
  21.         if (this.locations != null) ...{   
  22.             PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();   
  23.             for (int i = 0; i < this.locations.length; i++) ...{   
  24.                 Resource location = this.locations[i];   
  25.                 if (logger.isInfoEnabled()) ...{   
  26.                     logger.info("Loading properties file from " + location);   
  27.                 }   
  28.                 InputStream is = null;   
  29.                 try{   
  30.                     is = location.getInputStream();   
  31.                         //③ 加载密钥   
  32.                     Key key = DESEncryptUtil.getKey(keyLocation.getInputStream());   
  33.                     //④ 对属性文件进行解密   
  34.                     is = DESEncryptUtil.doDecrypt(key, is);   
  35.                     //⑤ 将解密后的属性流装载到props中   
  36.                     if(fileEncoding != null)...{   
  37.                         propertiesPersister.load(props,new InputStreamReader(is,fileEncoding));   
  38.                     }else {   
  39.                         propertiesPersister.load(props ,is);   
  40.                     }   
  41.                 } finally{   
  42.                     if (is != null)   
  43.                         is.close();   
  44.                 }   
  45.             }   
  46.         }   
  47.     }   
  48.     }   
  49. }  
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.Key;
import java.util.Properties;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.Resource;
import org.springframework.util.DefaultPropertiesPersister;
import org.springframework.util.PropertiesPersister;
public class DecryptPropertyPlaceholderConfigurer
        extends PropertyPlaceholderConfigurer ...{
    private Resource[] locations;   //① 重新定义父类中的这个同名属性
    private Resource keyLocation; //② 用于指定密钥文件
    public void setKeyLocation(Resource keyLocation) ...{
        this.keyLocation = keyLocation;
    }
    public void setLocations(Resource[] locations) ...{
        this.locations = locations;
    }
    public void loadProperties(Properties props) throws IOException ...{
        if (this.locations != null) ...{
            PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();
            for (int i = 0; i < this.locations.length; i++) ...{
                Resource location = this.locations[i];
                if (logger.isInfoEnabled()) ...{
                    logger.info("Loading properties file from " + location);
                }
                InputStream is = null;
                try{
                    is = location.getInputStream();
                        //③ 加载密钥
                    Key key = DESEncryptUtil.getKey(keyLocation.getInputStream());
                    //④ 对属性文件进行解密
                    is = DESEncryptUtil.doDecrypt(key, is);
                    //⑤ 将解密后的属性流装载到props中
                    if(fileEncoding != null)...{
                        propertiesPersister.load(props,new InputStreamReader(is,fileEncoding));
                    }else {
                        propertiesPersister.load(props ,is);
                    }
                } finally{
                    if (is != null)
                        is.close();
                }
            }
        }
    }
    }
}

 

    对locations指定的属性文件流数据进行额外的解密工作,解密后再装载到props中。比起 PropertyPlaceholderConfigurer,我们只做了额外的一件事:装载前对属性资源进行解密。

    在代码清单 2的③和④处,我们使用了一个DES解密的工具类对加密的属性文件流进行解密。
    对文件进行对称加密的算法很多,一般使用DES对称加密算法,因为它速度很快,破解困难,DESEncryptUtil不但提供了DES解密功能,还提供了DES加密的功能,因为属性文件在部署前必须经常加密:
    代码清单 3 加密解密工具类

Java代码 复制代码
  1. public class DESEncryptUtil ...{   
  2.     public static Key createKey() throws NoSuchAlgorithmException {//创建一个密钥   
  3.         Security.insertProviderAt(new com.sun.crypto.provider.SunJCE(), 1);   
  4.         KeyGenerator generator = KeyGenerator.getInstance("DES");   
  5.         generator.init(new SecureRandom());   
  6.         Key key = generator.generateKey();   
  7.         return key;   
  8.     }   
  9.     public static Key getKey(InputStream is) {   
  10.         try{   
  11.             ObjectInputStream ois = new ObjectInputStream(is);   
  12.             return (Key) ois.readObject();   
  13.         } catch (Exception e) ...{   
  14.             e.printStackTrace();   
  15.             throw new RuntimeException(e);   
  16.         }   
  17.     }   
  18.     private static byte[] doEncrypt(Key key, byte[] data) {//对数据进行加密   
  19.         try {   
  20.             Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");   
  21.             cipher.init(Cipher.ENCRYPT_MODE, key);   
  22.             byte[] raw = cipher.doFinal(data);   
  23.             return raw;   
  24.         } catch (Exception e) {   
  25.             e.printStackTrace();   
  26.             throw new RuntimeException(e);   
  27.         }   
  28.     }   
  29.     public static InputStream doDecrypt(Key key, InputStream in) {//对数据进行解密   
  30.         try {   
  31.             Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");   
  32.             cipher.init(Cipher.DECRYPT_MODE, key);   
  33.             ByteArrayOutputStream bout = new ByteArrayOutputStream();   
  34.             byte[] tmpbuf = new byte[1024];   
  35.             int count = 0;   
  36.             while ((count = in.read(tmpbuf)) != -1) {   
  37.                 bout.write(tmpbuf, 0, count);   
  38.                 tmpbuf = new byte[1024];   
  39.             }   
  40.             in.close();   
  41.             byte[] orgData = bout.toByteArray();   
  42.             byte[] raw = cipher.doFinal(orgData);   
  43.             ByteArrayInputStream bin = new ByteArrayInputStream(raw);   
  44.             return bin;   
  45.         } catch (Exception e) {   
  46.             e.printStackTrace();   
  47.             throw new RuntimeException(e);   
  48.         }   
  49.     }   
  50.     public static void main(String[] args) throws Exception {//提供了Java命令使用该工具的功能   
  51.         if (args.length == 2 && args[0].equals("key")) {// 生成密钥文件   
  52.             Key key = DESEncryptUtil.createKey();   
  53.             ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(args[1]));   
  54.             oos.writeObject(key);   
  55.             oos.close();   
  56.             System.out.println("成功生成密钥文件。");   
  57.         } else if (args.length == 3 && args[0].equals("encrypt")) {//对文件进行加密   
  58.             File file = new File(args[1]);   
  59.             FileInputStream in = new FileInputStream(file);   
  60.             ByteArrayOutputStream bout = new ByteArrayOutputStream();   
  61.             byte[] tmpbuf = new byte[1024];   
  62.             int count = 0;   
  63.             while ((count = in.read(tmpbuf)) != -1) {   
  64.                 bout.write(tmpbuf, 0, count);   
  65.                 tmpbuf = new byte[1024];   
  66.             }   
  67.             in.close();   
  68.             byte[] orgData = bout.toByteArray();   
  69.             Key key = getKey(new FileInputStream(args[2]));   
  70.             byte[] raw = DESEncryptUtil.doEncrypt(key, orgData);   
  71.             file = new File(file.getParent() + "//en_" + file.getName());   
  72.             FileOutputStream out = new FileOutputStream(file);   
  73.             out.write(raw);   
  74.             out.close();   
  75.             System.out.println("成功加密,加密文件位于:"+file.getAbsolutePath());   
  76.         } else if (args.length == 3 && args[0].equals("decrypt")) {//对文件进行解密   
  77.             File file = new File(args[1]);   
  78.             FileInputStream fis = new FileInputStream(file);   
  79.             Key key = getKey(new FileInputStream(args[2]));   
  80.             InputStream raw = DESEncryptUtil.doDecrypt(key, fis);   
  81.             ByteArrayOutputStream bout = new ByteArrayOutputStream();   
  82.             byte[] tmpbuf = new byte[1024];   
  83.             int count = 0;   
  84.             while ((count = raw.read(tmpbuf)) != -1) {   
  85.                 bout.write(tmpbuf, 0, count);   
  86.                 tmpbuf = new byte[1024];   
  87.             }   
  88.             raw.close();   
  89.             byte[] orgData = bout.toByteArray();   
  90.             file = new File(file.getParent() + "//rs_" + file.getName());   
  91.             FileOutputStream fos = new FileOutputStream(file);   
  92.             fos.write(orgData);   
  93.             System.out.println("成功解密,解密文件位于:"+file.getAbsolutePath());   
  94.         }   
  95.     }   
  96. }    
public class DESEncryptUtil ...{
    public static Key createKey() throws NoSuchAlgorithmException {//创建一个密钥
        Security.insertProviderAt(new com.sun.crypto.provider.SunJCE(), 1);
        KeyGenerator generator = KeyGenerator.getInstance("DES");
        generator.init(new SecureRandom());
        Key key = generator.generateKey();
        return key;
    }
    public static Key getKey(InputStream is) {
        try{
            ObjectInputStream ois = new ObjectInputStream(is);
            return (Key) ois.readObject();
        } catch (Exception e) ...{
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    private static byte[] doEncrypt(Key key, byte[] data) {//对数据进行加密
        try {
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] raw = cipher.doFinal(data);
            return raw;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    public static InputStream doDecrypt(Key key, InputStream in) {//对数据进行解密
        try {
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key);
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] tmpbuf = new byte[1024];
            int count = 0;
            while ((count = in.read(tmpbuf)) != -1) {
                bout.write(tmpbuf, 0, count);
                tmpbuf = new byte[1024];
            }
            in.close();
            byte[] orgData = bout.toByteArray();
            byte[] raw = cipher.doFinal(orgData);
            ByteArrayInputStream bin = new ByteArrayInputStream(raw);
            return bin;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    public static void main(String[] args) throws Exception {//提供了Java命令使用该工具的功能
        if (args.length == 2 && args[0].equals("key")) {// 生成密钥文件
            Key key = DESEncryptUtil.createKey();
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(args[1]));
            oos.writeObject(key);
            oos.close();
            System.out.println("成功生成密钥文件。");
        } else if (args.length == 3 && args[0].equals("encrypt")) {//对文件进行加密
            File file = new File(args[1]);
            FileInputStream in = new FileInputStream(file);
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] tmpbuf = new byte[1024];
            int count = 0;
            while ((count = in.read(tmpbuf)) != -1) {
                bout.write(tmpbuf, 0, count);
                tmpbuf = new byte[1024];
            }
            in.close();
            byte[] orgData = bout.toByteArray();
            Key key = getKey(new FileInputStream(args[2]));
            byte[] raw = DESEncryptUtil.doEncrypt(key, orgData);
            file = new File(file.getParent() + "//en_" + file.getName());
            FileOutputStream out = new FileOutputStream(file);
            out.write(raw);
            out.close();
            System.out.println("成功加密,加密文件位于:"+file.getAbsolutePath());
        } else if (args.length == 3 && args[0].equals("decrypt")) {//对文件进行解密
            File file = new File(args[1]);
            FileInputStream fis = new FileInputStream(file);
            Key key = getKey(new FileInputStream(args[2]));
            InputStream raw = DESEncryptUtil.doDecrypt(key, fis);
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] tmpbuf = new byte[1024];
            int count = 0;
            while ((count = raw.read(tmpbuf)) != -1) {
                bout.write(tmpbuf, 0, count);
                tmpbuf = new byte[1024];
            }
            raw.close();
            byte[] orgData = bout.toByteArray();
            file = new File(file.getParent() + "//rs_" + file.getName());
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(orgData);
            System.out.println("成功解密,解密文件位于:"+file.getAbsolutePath());
        }
    }
}  

    解密工作主要涉及到两个类Cipher和Key,前者是加密器,可以通过init()方法设置工作模式和密钥,在这里,我们设置为解密工作模式:Cipher.DECRYPT_MODE。Cipher通过doFinal()方法对字节数组进行加密或解密。

    要完成属性文件的加密工作,首先,必须获取一个密钥文件,然后才能对明文的属性文件进行加密。如果需要调整属性文件的信息,你必须执行相反的过程,即用密钥对加密后的属性文件进行解密,调整属性信息后,再将其加密。
DESEncryptUtil 工具类可以完成以上所提及的三个工作:
1、生成一个密钥文件
java com.baobaotao.DESEncryptUtil key D:/key.dat
第一个参数为key,表示创建密钥文件,第二个参数为生成密钥文件的保存地址。
2、用密钥文件对属性文件进行加密
java com.baobaotao.DESEncryptUtil encrypt d:/test.properties d:/key.dat
第一个参数为encrypt,表示加密,第二个参数为需要加密的属性文件,第三个参数为密钥文件。如果加密成功,将生成 en_test.properties的加密文件。
3、用密钥文件对加密后的属性文件进行解密
java com.baobaotao.DESEncryptUtil decrypt d:/test.properties d:/key.dat
第一个参数为decrypt,表示解密,第二个参数为需要解密的属性文件,第三个参数为密钥文件。如果加密成功,将生成 rs_test.properties的解密文件。

    在Spring中配置加密属性文件
    假设我们通过DESEncryptUtil 工具类创建了一个key.bat密钥,并对car.properties属性进行加密,生成加密文件en_car.properties。下面,我们通过 DecryptPropertyPlaceholderConfigurer增强类进行配置,让Spring容器支持加密的属性文件:
    假设我们通过DESEncryptUtil 工具类创建了一个key.bat密钥,并对car.properties属性进行加密,生成加密文件en_car.properties。下面,我们通过 DecryptPropertyPlaceholderConfigurer增强类进行配置,让Spring容器支持加密的属性文件:

Xml代码 复制代码
  1. <bean class="com.baobaotao.place.DecryptPropertyPlaceholderConfigurer"> ①   
  2.     <property name="locations">  
  3.         <list>  
  4.             <value>classpath:com/baobaotao/en_car.properties</value>  
  5.         </list>  
  6.     </property>  
  7.     <property name="keyLocation" value="classpath:com/baobaotao/key.dat" />  
  8.     <property name="fileEncoding" value="utf-8" />  
  9. </bean>  
  10. <bean id="car" class="com.baobaotao.place.Car"> ②   
  11.     <property name="brand" value="${brand}" />  
  12.     <property name="maxSpeed" value="${maxSpeed}" />  
  13.     <property name="price" value="${price}" />  
  14. </bean>  

     注意①处的配置,我们使用自己编写的DecryptPropertyPlaceholderConfigurer替代Spring的 PropertyPlaceholderConfigurer,由于前者对属性文件进行了特殊的解密处理,因此②处的car Bean也可以引用到加密文件en_car.properties中的属性项。

    小结
    要Spring配置时,将一些重要的信息独立到属性文件中是比较常见的做法,Spring只支持明文存放的属性文件,在某些场合下,我们可以希望对属性文件加密保存,以保证关键信息的安全。通过扩展PropertyPlaceholderConfigurer,在属性文件流加载后应用前进行解密就可以很好地解决这个问题了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值