配置檔案項密碼加密與解密
阿新 • • 發佈:2019-02-09
- 背景:最近在部署web專案的時候由於用到了Tomcat,其連線資料庫的資料來源沒有配置在其中(官網將是可以配置的,目前在用weblogic是直接配置資料來源在console客戶端的),考慮到資料庫連線密碼直接配置在xml中,專案流轉出現密碼洩露隱患,這裡直接對密碼進行AES加密
- 實操:
package com.szpl.common;
import java.io.IOException;
import java.sql.Connection;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
1. @author lix
*加密用的key可以用26個字母和數字組成,最好不要用保留字元,雖然不會錯,至於怎麼裁決,個人看情況而定
*如此處理AES-128-CBC加密模式,key需要16位
*這裡主要是對資料庫連線使用者名稱及密碼進行加密解密
*/
public class AES {
private static String src = "plansuplis";
public static void main(String[] args) throws Exception {
//System.out.println(AES.Encrypt(src, "0807060504030201"));
//System.out.println(AES.Decrypt(AES.Encrypt(src, "0807060504030201"), "0807060504030201"));
String password = SystemConfig.getSystemConfigInstance().getConfigItemByKey("orc_password");
password = AES.Decrypt(password, "0807060504030201" );//解密
System.out.println(password);
}
// 加密
public static String Encrypt(String sSrc, String sKey) throws Exception {
if (sKey == null) {
System.out.print("Key為空null");
return null;
}
// 判斷Key是否為16位
if (sKey.length() != 16) {
System.out.print("Key長度不是16位");
return null;
}
byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"演算法/模式/補碼方式"
IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());//使用CBC模式,需要一個向量iv,可增加加密演算法的強度
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes());
return org.apache.commons.codec.binary.Base64.encodeBase64String(encrypted);//此處使用BAES64做轉碼功能,同時能起到2次加密的作用。
}
// 解密
public static String Decrypt(String sSrc, String sKey) throws Exception {
try {
// 判斷Key是否正確
if (sKey == null) {
System.out.print("Key為空null");
return null;
}
// 判斷Key是否為16位
if (sKey.length() != 16) {
System.out.print("Key長度不是16位");
return null;
}
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = org.apache.commons.codec.binary.Base64.decodeBase64(sSrc);//先用bAES64解密
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
} catch (Exception ex) {
System.out.println(ex.toString());
return null;
}
}
}
- 效果:
#ye wu shu ju ku lian jie
orc_driver = oracle.jdbc.driver.OracleDriver
orc_url = jdbc:oracle:thin:@192.168.110.2:1521:oraplan
orc_username = suplis
orc_password = s1Dxf1XWoH46gy+VHJlZ2Q==
其中密碼被加密。只需要在系統中解密即可。