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

原创整理不易,转载请注明出处:java
spring中对properties属性文件加密及其解密

代码下载地址:http://www.zuidaima.com/share/1781588957400064.htm

加密类:

package com.zuidaima.commons.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

/**
 * <ul>
 * <li>Title:[DESEncryptUtil]</li>
 * <li>Description: [加密码解密类]</li>
 * <li>Copyright 2009 RoadWay Co., Ltd.</li>
 * <li>All right reserved.</li>
 * <li>Created by [Huyvanpull] [Jul 19, 2010]</li>
 * <li>Midified by [修改人] [修改时间]</li>
 * </ul>
 *
 * @version 1.0
 */
public class DESEncryptUtil
{
    public static void main(String[] args) throws Exception
    {
        /** 生成KEY */
        String operatorType = "key";
        String keyFilePath = "D:/key.k";
        DESEncryptUtil.test(keyFilePath, null, operatorType);

        /** 加密 */
        operatorType = "encrypt";
        String sourceFilePath = "D:/jdbc_official.properties";
        DESEncryptUtil.test(keyFilePath, sourceFilePath, operatorType);

        /** 解密 */
        operatorType = "decrypt";
        sourceFilePath = "D:/en_jdbc_official.properties";
        DESEncryptUtil.test(keyFilePath, sourceFilePath, operatorType);
    }
    /**
     * <ul>
     * <li>Description:[创建一个密钥]</li>
     * <li>Created by [Huyvanpull] [Jul 19, 2010]</li>
     * <li>Midified by [修改人] [修改时间]</li>
     * </ul>
     *
     * @return
     * @throws NoSuchAlgorithmException
     */
    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;
    }

    /**
     * <ul>
     * <li>Description:[根据流得到密钥]</li>
     * <li>Created by [Huyvanpull] [Jul 19, 2010]</li>
     * <li>Midified by [修改人] [修改时间]</li>
     * </ul>
     *
     * @param is
     * @return
     */
    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);
        }
    }

    /**
     * <ul>
     * <li>Description:[对数据进行加密]</li>
     * <li>Created by [Huyvanpull] [Jul 19, 2010]</li>
     * <li>Midified by [修改人] [修改时间]</li>
     * </ul>
     *
     * @param key
     * @param data
     * @return
     */
    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);
        }
    }

    /**
     * <ul>
     * <li>Description:[对数据进行解密]</li>
     * <li>Created by [Huyvanpull] [Jul 19, 2010]</li>
     * <li>Midified by [修改人] [修改时间]</li>
     * </ul>
     *
     * @param key
     * @param in
     * @return
     */
    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);
        }
    }

    private static void test(String keyFilePath, String sourceFilePath,
            String operatorType) throws Exception
    {
        // 提供了Java命令使用该工具的功能
        if (operatorType.equalsIgnoreCase("key"))
        {
            // 生成密钥文件
            Key key = DESEncryptUtil.createKey();
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(keyFilePath));
            oos.writeObject(key);
            oos.close();
            System.out.println("成功生成密钥文件" + keyFilePath);
        }
        else if (operatorType.equalsIgnoreCase("encrypt"))
        {
            // 对文件进行加密
            File file = new File(sourceFilePath);
            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(keyFilePath));
            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 (operatorType.equalsIgnoreCase("decrypt"))
        {
            // 对文件进行解密
            File file = new File(sourceFilePath);
            FileInputStream fis = new FileInputStream(file);

            Key key = getKey(new FileInputStream(keyFilePath));
            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());
        }
    }
}

DecryptPropertyPlaceholderConfigurer.java

package com.zuidaima.spring;

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;

import com.zuidaima.commons.util.DESEncryptUtil;

public class DecryptPropertyPlaceholderConfigurer extends
        PropertyPlaceholderConfigurer
{
    private Resource[] locations;

    private Resource keyLocation;

    private String fileEncoding;

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

配置文件:

<!-- 加密码属性文件 -->
    <bean id="myPropertyConfigurer"
        class="com.zuidaima.spring.DecryptPropertyPlaceholderConfigurer">
        <property name="locations">
            <list><value>classpath*:spring_config/jdbc_official.databaseinfo</value></list>
        </property>
        <property name="fileEncoding" value="UTF-8"/>
        <property name="keyLocation" value="classpath:spring_config/key.key" />
    </bean>

java spring中对properties属性文件加密及其解密,布布扣,bubuko.com

时间: 2024-10-15 05:11:01

java spring中对properties属性文件加密及其解密的相关文章

spring加载properties属性文件到内存

1. CustomPropertyConfigurer.java package propertyconfig; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.Map.Entry; import org.springframework.beans.BeansException; import org.springframework.beans.factor

java中.properties属性文件的使用案例源码

一.描述 java中的.properties属性文件的正确使用可以解决很多问题,比如一个登录界面要做一个记住用户登录过的用户名和密码并且放在本地方便用户登录. 二.操作步骤 1.  打开eclipse工程文件目录下的XX.properties文件,如果没有就创建一个 2. 以键-值对的方式记录用户最近登录过的用户名--密码,添加一个键值对 3. 移除一个键-值对 4. 保存这个属性文件 5. 获取属性文件的所有键 6. 获取指定键的属性值 二.源代码 //在工作主目录下(即eclipse项目目录

Java读取利用java.util类Properties读取resource下的properties属性文件

说明:upload.properties属性文件在resources下 import java.io.IOException;import java.io.InputStream;import java.util.Properties;import java.util.ResourceBundle; public class Test { private static Properties pro ; static{ InputStream inputStream = Test.class.ge

Code片段 : .properties属性文件操作工具类 &amp; JSON工具类

摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “贵专” — 泥瓦匠 一.java.util.Properties API & 案例 java.util.Properties 是一个属性集合.常见的api有如下: load(InputStream inStream)  从输入流中读取属性 getProperty(String key)  根据key,获取属性值 getOrDefault(Object key, V defaultValue)

解决读写properties属性文件

package com.kzkj.wx.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import

Spring 中注入 properties 中的值

1 <bean id="ckcPlaceholderProperties" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> 2 <property name="locations"> 3 <list> 4 <value>classpath:default.properties<

spring中使用parent属性来减少配置

在基于spring框架开发的项目中,如果有多个bean都是一个类的实力,如配置多个数据源时,大部分配置的属性都一样,只有少部分不一样,经常是copy上一个的定义,然后修改不一样的地方.其实spring bean定义也可以和对象一样进行继承. 示例如下:  <bean id="testBeanParent"  abstract="true"  class="com.wanzheng90.bean.TestBean">         &

java开发中截取上传文件的文件名和后缀名

java开发中截取上传文件的文件名和后缀名 /** * Return the extension portion of the file's name . * * @see #getExtension */ public static String getExtension(File f) { return (f != null) ? getExtension(f.getName()) : ""; } public static String getExtension(String f

怎么给工作中重要的pdf文件加密

怎么给工作中重要的pdf文件加密?大家在工作中都会接触一些合作项目的重要文件.这些重要文件有时候就会影响整个合作项目的成功与否.因此大家对于这些重要文件的保护意识都非常强.因为pdf文件属于安全性较高的文件格式,所以大家就会将重要的工作文件以pdf格式保存.并且为了防患于未然,还会给pdf文件进行加密.在接下来得文章内容里,就会告诉大家如何给工作中的pdf文件添加密码. 1.搜索关键词pdf在线加密.大家打开自己电脑中的百度浏览器,然后在其中查找关键词pdf在线加密,接着点击进入搜索到得相关页面