欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android數(shù)據(jù)傳輸中的參數(shù)加密代碼示例

 更新時(shí)間:2017年11月22日 11:17:14   作者:ljtyzhr  
這篇文章主要介紹了Android數(shù)據(jù)傳輸中的參數(shù)加密代碼示例,具有一定參考價(jià)值,需要的朋友可以了解下。

Android開發(fā)中,難免會(huì)遇到需要加解密一些數(shù)據(jù)內(nèi)容存到本地文件、或者通過網(wǎng)絡(luò)傳輸?shù)狡渌?wù)器和設(shè)備的問題,但并不是使用了加密就絕對(duì)安全了,如果加密函數(shù)使用不正確,加密數(shù)據(jù)很容易受到逆向破解攻擊。還有很多開發(fā)者沒有意識(shí)到的加密算法的問題。

1、數(shù)據(jù)傳輸

1)、http請(qǐng)求中,最常用的方法有兩種:get和post;一般post請(qǐng)求適合做提交,而get請(qǐng)求適合做請(qǐng)求數(shù)據(jù)

2)、數(shù)據(jù)的加密,大概有三種常用的:AES,DES,Base64

2、Base64加密

這里使用的aes加密,然后再將字符串使用Base64編碼,其中有增加向量,是為了提高加密破解難度,一段參數(shù)加密的方法如下:

/** 
   * 對(duì)post請(qǐng)求數(shù)據(jù)進(jìn)行加密 
   * @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)請(qǐng)求的字符串被截?cái)啵ト℃溄又?,得到一段空格的字符串。?jīng)過分析,其實(shí)這里是換行。。。。。

解決的方法是,在請(qǐng)求的時(shí)候,將輸出的字符串,做如下處理:

將  
android.util.Base64.encodeToString(input, Base64.DEFAULT) 
換成 
android.util.Base64.encodeToString(input, Base64.NO_WRAP); 

2)除了上面的是因?yàn)閾Q行之外,其實(shí)也真的存在空格的情況,這個(gè)時(shí)候,可以使用替換,如下:

// 加密: 
byte[] bodyBytes = RequestManager.encryptParams(hashMap); 
// 使用base64encode做最后的加密 
String result = new BASE64Encoder().encode(bodyBytes); 
String ans_url = headUrl + result.replaceAll("\n",""); 

4、總結(jié)

base64encode編碼會(huì)在76位之后,將字符串截?cái)?。在含有中文字符串的情況下,會(huì)出現(xiàn)加號(hào)被替換成空格的情況。

以上就是本文關(guān)于Android數(shù)據(jù)傳輸中的參數(shù)加密代碼示例的全部?jī)?nèi)容,希望對(duì)大家有所幫助,感興趣的朋友可以繼續(xù)參閱本站:

Android開發(fā)實(shí)現(xiàn)文件關(guān)聯(lián)方法介紹

Android分包MultiDex策略詳解

如有不足之處,歡迎留言指出。

相關(guān)文章

最新評(píng)論