`
cpu
  • 浏览: 165372 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

数据库连接加密 配置文件加密

    博客分类:
  • Java
阅读更多
重写连接池的setPassword()方法.
写密文解析成明文.

public synchronized void setPassword(String password) {
		super.setPassword(Crypto.decrypt(password));
	}


  <bean id="dataSource" class="com.cc.utils.MyDataSource" destroy-method="close">
        <property name="driverClassName" value="${oracle.driverClassName}"/>
        <property name="url" value="${oracle.url}"/>
        <property name="username" value="${oracle.username}"/>
        <property name="password" value="${oracle.password}"/>        
    </bean>
    



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

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

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

public class Crypto {

	private static Key key;
	private static final String strKey = "key";
	
	
	private static void setKey(String strKey) {
		try {
			KeyGenerator generator = KeyGenerator.getInstance("DES");
			generator.init(new SecureRandom(strKey.getBytes()));
			key = generator.generateKey();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static byte[] getCipherFromClear(byte[] byteClear) {
		Cipher cipher = null;
		byte[] byteCipher = null;
		
		try {
			cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byteCipher = cipher.doFinal(byteClear);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			cipher = null;
		}
		
		return byteCipher;
	}
	
	/**
	 * 加密
	 * @param plainStr
	 * @return
	 */
	public static String encrypt(String plainStr) {
		BASE64Encoder base64Encode = new BASE64Encoder();
		String strCipher = "";
		byte[] bClear = null;
		byte[] bCipher = null;
		
		setKey(strKey);
		
		try {
			bClear = plainStr.getBytes("UTF-8");
			bCipher = getCipherFromClear(bClear);
			strCipher = base64Encode.encodeBuffer(bCipher);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strCipher;
	}
	
	private static byte[] getClearFromCipher(byte[] byteCipher) {
		
		Cipher cipher = null;
		byte[] byteClear = null;
		
		try {
			cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.DECRYPT_MODE, key);
			byteClear = cipher.doFinal(byteCipher);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		return byteClear;
	}
	
	
	/**
	 * 解密
	 * @param strCipher
	 * @return
	 */
	public static String decrypt(String strCipher) {
		BASE64Decoder base64Decode = new BASE64Decoder();
		String strClear = "";
		byte[] byteCipher = null;
		byte[] byteClear = null;
		
		setKey(strKey);
		
		try {
			byteCipher = base64Decode.decodeBuffer(strCipher);
			byteClear = getClearFromCipher(byteCipher);
			strClear = new String(byteClear, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return strClear;
	}
	
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics