DES 加密Demo

DES加密工具类:

package com.sharp.cxf.utils;

import java.security.Key;
import java.security.SecureRandom;

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

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 类 名 称: DESUtils
 * 类 描 述: 加密解密工具类
 * 创 建 人: peng.xiao
 * 创建时间: 2013-7-21 上午8:04:51
 *
 * 修 改 人:  peng.xiao
 * 操作时间: 2013-7-21 上午8:04:51
 * 操作原因: 
 * 
 */
public class DESUtils {
	
	private static Key key;
	private static String KEY_STR="myKey";
	
	static{
		try{
			KeyGenerator generator = KeyGenerator.getInstance("DES");
			generator.init(new SecureRandom(KEY_STR.getBytes()));
			key = generator.generateKey();
			generator = null;
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 方法描述:  获得des加密后的字符串
	 * 作    者:  peng.xiao
	 * 日    期: 2013-7-21-上午8:01:08
	 * @param str
	 * @return 
	 * 返回类型: String
	*/
	public static String getEncryptString(String str){
		try{
			BASE64Encoder encode = new BASE64Encoder();
			byte[] strBytes = str.getBytes("UTF8");
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] encryptStrBytes = cipher.doFinal(strBytes);
			return encode.encode(encryptStrBytes);
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}
	
	
	/**
	 * 方法描述:  获得解密后的字符串
	 * 作    者:  peng.xiao
	 * 日    期: 2013-7-21-上午8:04:15
	 * @param str
	 * @return 
	 * 返回类型: String
	*/
	public static String getDecryptString(String str){
		BASE64Decoder decode = new BASE64Decoder();
		try{
			byte[] strBytes = decode.decodeBuffer(str);
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] decryptStrBytes = cipher.doFinal(strBytes);
			return new String(decryptStrBytes,"UTF8");
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}
	
	public static void main(String[] args) {
		System.out.println(getEncryptString("sharp"));
	}
}

属性文件重写:

package com.sharp.cxf.utils;

import java.util.ArrayList;
import java.util.List;

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

public class EncryPropertyConfigurer extends PropertyOverrideConfigurer{

	private List<String> entryProName = new ArrayList<String>();
	
	public List<String> getEntryProName() {
		return entryProName;
	}

	public void setEntryProName(List<String> entryProName) {
		this.entryProName = entryProName;
	}

	@Override
	protected void processKey(ConfigurableListableBeanFactory factory,
			String key, String value) throws BeansException {
		if(entryProName.contains(key)){
			value = DESUtils.getDecryptString(value);
		}
		super.processKey(factory, key, value);
	}
}


你可能感兴趣的:(DES 加密Demo)