利用反射機制建立工具類對資料進行加密和解密
阿新 • • 發佈:2018-12-06
對資料庫的資料進行加密,包括使用者資料、專案資料、聊天資料等,需要在插入表的的時候進行加密,查詢的時候進行解密。利用java的反射機制,建立以下工具類,對資料進行加解密。
public class CryptoUtil {
/**
* 加密、解密方法
* @param obj要加密或解密的物件
* @param type 1加密操作,2解密操作
* @throws Exception
*/
public static void cryptoObject(Object obj,Integer type) throws Exception{
Class cls = obj.getClass();
//思路:獲取object的屬性名稱-->獲取object的屬性值-->對值進行加密/解密-->將加密後的值set回屬性中
Field[] fields = cls.getDeclaredFields();
if(fields!=null&&fields.length>0){
for(Field field : fields){
field.setAccessible(true);//設定這些屬性是可訪問的
Type fieldType = field.getGenericType();//返回屬性聲的Type型別
// Class fieldType = field.getType();//獲取屬性宣告時型別物件(返回class物件)
if(fieldType.toString().equals("class java.lang.String")){//只對String型別的資料加密
String fieldName = field.getName();
String fieldValue = (String)field.get(obj);//獲取屬性的值
if(fieldValue!=null&&!"".equals(fieldValue)){
String encValue = null;
switch (type) {
case 1:
encValue = AESUtil.encrypt(fieldValue);//進行加密
break;
case 2:
encValue = AESUtil.decrypt(fieldValue);//進行加密
break;
}
field.set(obj, encValue);//設定屬性的值
}
}
}
}
}
}
加密和解密的方法AESUtil.encrypt()、AESUtil.decrypt()參考:https://blog.csdn.net/qq_23888451/article/details/84658360
遇到的問題:
1.java.lang.IllegalAccessException: Class com.zz.util.CryptoUtil can not access a member of class com.zz.manage.model.Message with modifiers “private”。
Message類的屬性設定為private,如果不設定field.setAccessible(true),將會報這個錯誤。
2.field.getGenericType()和field.getType()的區別
- 返回的型別不一樣,一個是Class物件一個是Type介面
- 如果屬性是一個泛型,從getType()只能得到這個屬性的介面型別。但是getGenericType()還可以得到這個泛型的引數型別
- getGenericType()如果當前屬性有簽名屬性型別就返回,都則就返回Field.getType()
- 本知識點參考反射API