Android開發(fā)中,難免會遇到需要加解密一些數(shù)據(jù)內(nèi)容存到本地文件、或者通過網(wǎng)絡(luò)傳輸?shù)狡渌?wù)器和設(shè)備的問題,但并不是使用了加密就絕對安全了,如果加密函數(shù)使用不正確,加密數(shù)據(jù)很容易受到逆向破解攻擊。還有很多開發(fā)者沒有意識到的加密算法的問題。
1、數(shù)據(jù)傳輸
1)、http請求中,最常用的方法有兩種:get和post;一般post請求適合做提交,而get請求適合做請求數(shù)據(jù)
2)、數(shù)據(jù)的加密,大概有三種常用的:AES,DES,Base64
2、android/203309.html">Base64加密
這里使用的aes加密,然后再將字符串使用Base64編碼,其中有增加向量,是為了提高加密破解難度,一段參數(shù)加密的方法如下:
/**    * 對post請求數(shù)據(jù)進行加密    * @param params    * @return    * @throws Throwable    */public static byte[] encryptParams(HashMap<String, String> params) throws Throwable{	if (params == null){		return null;	}	StringBuilder stringBuilder = new StringBuilder();	Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();	while (iterator.hasNext()){		Map.Entry<String,String> entry = iterator.next();		String key = entry.getKey();		String value = entry.getValue();		if (stringBuilder.length() > 0){			stringBuilder.append("&");		}		stringBuilder.append(key).append("=").append(Uri.encode(value));	}	byte[] buff = stringBuilder.toString().getBytes("utf-8");	byte[] iv = new byte[16];	Random random = new Random();	random.nextBytes(iv);	byte[] data = Aes.encrypt(buff,PASSWORD,iv);	ByteArrayOutputStream baos = new ByteArrayOutputStream();	baos.write(iv,0,iv.length);	baos.write(data,0,data.length);	byte[] out = baos.toByteArray();	try {		baos.close();	}	catch (Throwable e){		e.printStackTrace();	}	return out;}3、遇到問題
在使用Base64的過程中,遇到一些問題,如下:
1)請求的字符串被截斷,抓取鏈接之后,得到一段空格的字符串。經(jīng)過分析,其實這里是換行。。。。。
解決的方法是,在請求的時候,將輸出的字符串,做如下處理:
將 android/58546.html">android.util.Base64.encodeToString(input, Base64.DEFAULT) 換成 android.util.Base64.encodeToString(input, Base64.NO_WRAP);
2)除了上面的是因為換行之外,其實也真的存在空格的情況,這個時候,可以使用替換,如下:
// 加密: byte[] bodyBytes = RequestManager.encryptParams(hashMap); // 使用base64encode做最后的加密 String result = new BASE64Encoder().encode(bodyBytes); String ans_url = headUrl + result.replaceAll("/n",""); 4、總結(jié)
base64encode編碼會在76位之后,將字符串截斷。在含有中文字符串的情況下,會出現(xiàn)加號被替換成空格的情況。
以上就是本文關(guān)于Android數(shù)據(jù)傳輸中的參數(shù)加密代碼示例的全部內(nèi)容,希望對大家有所幫助,
如有不足之處,歡迎留言指出。
新聞熱點
疑難解答
圖片精選