http://www.oschina.net/code/piece_full?code=18383#30455
首先聲明的是,代碼不是本人寫的,感謝一下作者,只不過本人在做一個android客戶端,與服務器servlet接口通信的項目時,對協議作了des+base64加密處理,使用了該類,
期間遇到了一個比較糾結的問題,就是如果漢字存在於協議中,服務器加密,客戶端解密會出現亂碼,客戶端加密,服務器解密亦然。
以上問題的解決其實很簡單,只不過找問題原因的過程有點浪費時間,所以記錄在此,以告知其他有緣也用到該類的朋友,能夠節省一點寶貴的時間。
修改代碼如下:
/**
* Description 根據鍵值進行加密
*
* @param data
* @param key
* 加密鍵byte數組
* @return
* @throws Exception
*/
public static String encrypt(String data, String key) throws Exception {
byte[] bt = encrypt(data.getBytes("UTF-8"), key.getBytes());
String strs = new BASE64Encoder().encode(bt);
return strs;
}
/**
* Description 根據鍵值進行解密
*
* @param data
* @param key
* 加密鍵byte數組
* @return
* @throws IOException
* @throws Exception
*/
public static String decrypt(String data, String key) throws IOException,
Exception {
if (data == null)
return null;
BASE64Decoder decoder = new BASE64Decoder();
byte[] buf = decoder.decodeBuffer(data);
byte[] bt = decrypt(buf,key.getBytes());
return new String(bt, "UTF-8");
}
請留意,修改的兩處爲"UTF-8"的位置。
希望大夥沒有遇到這個問題。