java spring中对properties属性文件加密及其解密

加密类:

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.zuidaima.commons.util;  
  2.   
  3. import java.io.ByteArrayInputStream;  
  4. import java.io.ByteArrayOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.FileOutputStream;  
  8. import java.io.InputStream;  
  9. import java.io.ObjectInputStream;  
  10. import java.io.ObjectOutputStream;  
  11. import java.security.Key;  
  12. import java.security.NoSuchAlgorithmException;  
  13. import java.security.SecureRandom;  
  14. import java.security.Security;  
  15.   
  16. import javax.crypto.Cipher;  
  17. import javax.crypto.KeyGenerator;  
  18.   
  19. /** 
  20.  * <ul> 
  21.  * <li>Title:[DESEncryptUtil]</li> 
  22.  * <li>Description: [加密码解密类]</li> 
  23.  * <li>Copyright 2009 RoadWay Co., Ltd.</li> 
  24.  * <li>All right reserved.</li> 
  25.  * <li>Created by [Huyvanpull] [Jul 19, 2010]</li> 
  26.  * <li>Midified by [修改人] [修改时间]</li> 
  27.  * </ul> 
  28.  *  
  29.  * @version 1.0 
  30.  */  
  31. public class DESEncryptUtil  
  32. {  
  33.     public static void main(String[] args) throws Exception  
  34.     {  
  35.         /** 生成KEY */  
  36.         String operatorType = "key";  
  37.         String keyFilePath = "D:/key.k";  
  38.         DESEncryptUtil.test(keyFilePath, null, operatorType);  
  39.           
  40.         /** 加密 */  
  41.         operatorType = "encrypt";  
  42.         String sourceFilePath = "D:/jdbc_official.properties";  
  43.         DESEncryptUtil.test(keyFilePath, sourceFilePath, operatorType);  
  44.           
  45.         /** 解密 */  
  46.         operatorType = "decrypt";  
  47.         sourceFilePath = "D:/en_jdbc_official.properties";  
  48.         DESEncryptUtil.test(keyFilePath, sourceFilePath, operatorType);  
  49.     }  
  50.     /** 
  51.      * <ul> 
  52.      * <li>Description:[创建一个密钥]</li> 
  53.      * <li>Created by [Huyvanpull] [Jul 19, 2010]</li> 
  54.      * <li>Midified by [修改人] [修改时间]</li> 
  55.      * </ul> 
  56.      *  
  57.      * @return 
  58.      * @throws NoSuchAlgorithmException 
  59.      */  
  60.     public static Key createKey() throws NoSuchAlgorithmException  
  61.     {  
  62.         Security.insertProviderAt(new com.sun.crypto.provider.SunJCE(), 1);  
  63.         KeyGenerator generator = KeyGenerator.getInstance("DES");  
  64.         generator.init(new SecureRandom());  
  65.         Key key = generator.generateKey();  
  66.         return key;  
  67.     }  
  68.       
  69.     /** 
  70.      * <ul> 
  71.      * <li>Description:[根据流得到密钥]</li> 
  72.      * <li>Created by [Huyvanpull] [Jul 19, 2010]</li> 
  73.      * <li>Midified by [修改人] [修改时间]</li> 
  74.      * </ul> 
  75.      *  
  76.      * @param is 
  77.      * @return 
  78.      */  
  79.     public static Key getKey(InputStream is)  
  80.     {  
  81.         try  
  82.         {  
  83.             ObjectInputStream ois = new ObjectInputStream(is);  
  84.             return (Key) ois.readObject();  
  85.         }  
  86.         catch (Exception e)  
  87.         {  
  88.             e.printStackTrace();  
  89.             throw new RuntimeException(e);  
  90.         }  
  91.     }  
  92.       
  93.     /** 
  94.      * <ul> 
  95.      * <li>Description:[对数据进行加密]</li> 
  96.      * <li>Created by [Huyvanpull] [Jul 19, 2010]</li> 
  97.      * <li>Midified by [修改人] [修改时间]</li> 
  98.      * </ul> 
  99.      *  
  100.      * @param key 
  101.      * @param data 
  102.      * @return 
  103.      */  
  104.     private static byte[] doEncrypt(Key key, byte[] data)  
  105.     {  
  106.         try  
  107.         {  
  108.             Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");  
  109.             cipher.init(Cipher.ENCRYPT_MODE, key);  
  110.             byte[] raw = cipher.doFinal(data);  
  111.             return raw;  
  112.         }  
  113.         catch (Exception e)  
  114.         {  
  115.             e.printStackTrace();  
  116.             throw new RuntimeException(e);  
  117.         }  
  118.     }  
  119.       
  120.     /** 
  121.      * <ul> 
  122.      * <li>Description:[对数据进行解密]</li> 
  123.      * <li>Created by [Huyvanpull] [Jul 19, 2010]</li> 
  124.      * <li>Midified by [修改人] [修改时间]</li> 
  125.      * </ul> 
  126.      *  
  127.      * @param key 
  128.      * @param in 
  129.      * @return 
  130.      */  
  131.     public static InputStream doDecrypt(Key key, InputStream in)  
  132.     {  
  133.         try  
  134.         {  
  135.             Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");  
  136.             cipher.init(Cipher.DECRYPT_MODE, key);  
  137.             ByteArrayOutputStream bout = new ByteArrayOutputStream();  
  138.             byte[] tmpbuf = new byte[1024];  
  139.             int count = 0;  
  140.             while ((count = in.read(tmpbuf)) != -1)  
  141.             {  
  142.                 bout.write(tmpbuf, 0, count);  
  143.                 tmpbuf = new byte[1024];  
  144.             }  
  145.             in.close();  
  146.             byte[] orgData = bout.toByteArray();  
  147.             byte[] raw = cipher.doFinal(orgData);  
  148.             ByteArrayInputStream bin = new ByteArrayInputStream(raw);  
  149.             return bin;  
  150.         }  
  151.         catch (Exception e)  
  152.         {  
  153.             e.printStackTrace();  
  154.             throw new RuntimeException(e);  
  155.         }  
  156.     }  
  157.       
  158.     private static void test(String keyFilePath, String sourceFilePath,  
  159.             String operatorType) throws Exception  
  160.     {  
  161.         // 提供了Java命令使用该工具的功能  
  162.         if (operatorType.equalsIgnoreCase("key"))  
  163.         {  
  164.             // 生成密钥文件  
  165.             Key key = DESEncryptUtil.createKey();  
  166.             ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(keyFilePath));  
  167.             oos.writeObject(key);  
  168.             oos.close();  
  169.             System.out.println("成功生成密钥文件" + keyFilePath);  
  170.         }  
  171.         else if (operatorType.equalsIgnoreCase("encrypt"))  
  172.         {  
  173.             // 对文件进行加密  
  174.             File file = new File(sourceFilePath);  
  175.             FileInputStream in = new FileInputStream(file);  
  176.             ByteArrayOutputStream bout = new ByteArrayOutputStream();  
  177.             byte[] tmpbuf = new byte[1024];  
  178.             int count = 0;  
  179.             while ((count = in.read(tmpbuf)) != -1)  
  180.             {  
  181.                 bout.write(tmpbuf, 0, count);  
  182.                 tmpbuf = new byte[1024];  
  183.             }  
  184.             in.close();  
  185.             byte[] orgData = bout.toByteArray();  
  186.             Key key = getKey(new FileInputStream(keyFilePath));  
  187.             byte[] raw = DESEncryptUtil.doEncrypt(key, orgData);  
  188.             file = new File(file.getParent() + "\\en_" + file.getName());  
  189.             FileOutputStream out = new FileOutputStream(file);  
  190.             out.write(raw);  
  191.             out.close();  
  192.             System.out.println("成功加密,加密文件位于:" + file.getAbsolutePath());  
  193.         }  
  194.         else if (operatorType.equalsIgnoreCase("decrypt"))  
  195.         {  
  196.             // 对文件进行解密  
  197.             File file = new File(sourceFilePath);  
  198.             FileInputStream fis = new FileInputStream(file);  
  199.               
  200.             Key key = getKey(new FileInputStream(keyFilePath));  
  201.             InputStream raw = DESEncryptUtil.doDecrypt(key, fis);  
  202.             ByteArrayOutputStream bout = new ByteArrayOutputStream();  
  203.             byte[] tmpbuf = new byte[1024];  
  204.             int count = 0;  
  205.             while ((count = raw.read(tmpbuf)) != -1)  
  206.             {  
  207.                 bout.write(tmpbuf, 0, count);  
  208.                 tmpbuf = new byte[1024];  
  209.             }  
  210.             raw.close();  
  211.             byte[] orgData = bout.toByteArray();  
  212.             file = new File(file.getParent() + "\\rs_" + file.getName());  
  213.             FileOutputStream fos = new FileOutputStream(file);  
  214.             fos.write(orgData);  
  215.             System.out.println("成功解密,解密文件位于:" + file.getAbsolutePath());  
  216.         }  
  217.     }  
  218. }  


DecryptPropertyPlaceholderConfigurer.java

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.sedegree.utils;


    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;
        
        private String fileEncoding;
        
        private int order;
        
        private boolean ignoreUnresolvablePlaceholders;
        
        public void setKeyLocation(Resource keyLocation)
        {
            this.keyLocation = keyLocation;
        }
        
        public void setOrder(int order) {
        super.setOrder(order);
    this.order = order;
    }


    public void setLocations(Resource[] locations)
        {
    super.setLocations(locations);
            this.locations = locations;
        }


    public void setFileEncoding(String fileEncoding) {
    super.setFileEncoding(fileEncoding);
    this.fileEncoding = fileEncoding;
    }


    public void setIgnoreUnresolvablePlaceholders(
    boolean ignoreUnresolvablePlaceholders) {
    super.setIgnoreUnresolvablePlaceholders(ignoreUnresolvablePlaceholders);
    this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders;
    }


    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);
                        if (fileEncoding != null)
                        {
                            propertiesPersister.load(props, new InputStreamReader(
                                    is, fileEncoding));
                        }
                        else
                        {
                            propertiesPersister.load(props, is);
                        }
                    }
                    finally
                    {
                        if (is != null)
                        {
                            is.close();
                        }
                    }
                }
            }
        }
    }


配置文件(ignoreUnresolvablePlaceholders与order在有多个properties文件时需要配置):

  1. <bean id="myPropertyConfigurer2"
            class="com.sedegree.utils.DecryptPropertyPlaceholderConfigurer">
            <property name="order" value="1" />
            <property name="locations">
                <list>
                <value>classpath:en_cidu.properties</value>
                </list>
            </property>
            <property name="fileEncoding" value="UTF-8"/>
            <property name="keyLocation" value="classpath:key.key" />
            <property name="ignoreUnresolvablePlaceholders" value="true" />
        </bean>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值