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

重写连接池的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;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值