JAVA DES 对配置文件加密解密

最近遇上在搭建SSM框架的时候遇上数据库配置文件需加密的需求,网上搜罗资料自己写了一份。主要是给自己以后好找!同时也希望能帮助大家

这里是根据DES方式进行加密解密的类

package net.merise.mir.core.encrypt;
 
import java.io.IOException;
import java.security.SecureRandom;


import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;


import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
 
public class DESUtil {
 
    private final static String DES = "DES";
 
    public static void main(String[] args) throws Exception {
        String data = "mirundba";
        String key = "@abcdef@";
        System.err.println(encrypt(data, key));
    }
     
    /**
     * Description 根据键值进行加密
     * @param data 
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    public static String encrypt(String data, String key) throws Exception {
        byte[] bt = encrypt(data.getBytes(), key.getBytes());
        String strs = new BASE64Encoder().encode(bt);
        return strs;
    }
 
    /**
     * Description 根据键值进行解密
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String decrypt(String data, String key) throws IOException,
            Exception {
        if (data == null)
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] buf = decoder.decodeBuffer(data);
        byte[] bt = decrypt(buf,key.getBytes());
        return new String(bt);
    }
 
    /**
     * Description 根据键值进行加密
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
 
        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);
 
        // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);
 
        // Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance(DES);
 
        // 用密钥初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
 
        return cipher.doFinal(data);
    }
     
     
    /**
     * Description 根据键值进行解密
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
 
        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);
 
        // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);
 
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance(DES);
 
        // 用密钥初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
 
        return cipher.doFinal(data);
    }
}
这里是解密配置文件的类
<pre name="code" class="java">package net.merise.mir.core.encrypt;

import java.util.Properties;

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

public class DBConfigurer extends PropertyPlaceholderConfigurer {

	private final static String key = "@abcdef@";
	private final static String URL = "url";
	private final static String USER = "user";
	private final static String PASSWORD = "password";

	@Override
	protected void processProperties(
			ConfigurableListableBeanFactory beanFactory, Properties props)
			throws BeansException {

		String url = props.getProperty("url");
		if (url != null)
			try {
				props.setProperty(URL, DESUtil.decrypt(url, key));
			} catch (Exception e) {
				e.printStackTrace();
			}
		String user = props.getProperty("user");
		if (user != null)
			try {
				props.setProperty(USER, DESUtil.decrypt(user, key));
			} catch (Exception e) {
				e.printStackTrace();
			}
		
		String password = props.getProperty("password");
		if (password != null)
			try {
				props.setProperty(PASSWORD, DESUtil.decrypt(password, key));
			} catch (Exception e) {
				e.printStackTrace();
			}
		super.processProperties(beanFactory, props);
	}
}


 
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">接下来是配置Spring MVC</span>

	<!-- 属性文件读入,用于加密数据库配置文件 -->  
    <bean id="propertyConfigurer" class="net.maventec.mir.core.encrypt.DBConfigurer">  
        <property name="locations">  
            <list>  
                <value>classpath:config/db.properties</value>  
            </list>  
        </property>  
    </bean>

这是加密的配置文件

#数据库连接
driver=com.mysql.jdbc.Driver
url=aROE3XZWJAL1u0RpwMvhS1v0f8QyifbqaJDbkGu+b5iD8c/Pi3Ri+fSXkD9/1u1DYiKpIhgqce+aQfIw4cMq0g==
user=ZxV4aL2ZlUaudDFZJtxyAQ==
password=ZxV4aL2ZlUaudDFZJtxyAQ==

调用的配置文件

	<!-- 配置数据源 -->
	<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="jdbcUrl" value="${url}" />
		<property name="user" value="${user}" />
		<property name="driverClass" value="${driver}" />
		<property name="password" value="${password}" />

		<property name="minPoolSize" value="5" />
		<property name="maxPoolSize" value="50" />
		<property name="initialPoolSize" value="10" />
	</bean>

注意的是这两个的顺序不能反

	<!-- 属性文件读入,用于加密数据库配置文件 -->
	<bean id="propertyConfigurer" class="net.merise.mir.core.encrypt.DBConfigurer">
		<property name="locations">
			<list>
				<value>classpath:config/db.properties</value>
			</list>
		</property>
	</bean>
	
	<!-- 配置需要交给spring扫描管理的文件,一般是项目的配置文件(由context提供) -->
	<context:property-placeholder location="classpath:config/db.properties" />


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘岗强

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值