在開發應用過程中,客戶端與服務端經常需要進行數據傳輸,涉及到重要隱私信息時,開發者自然會想到對其進行加密,即使傳輸過程中被“有心人”截取,也不會將信息泄露。對于加密算法,相信不少開發者也有所耳聞,比如MD5加密,Base64加密,DES加密,AES加密,RSA加密等等。。可利用亦或,并,且,等進行簡單加密。
示例代碼中使用的^運算key=0x01,可自定義自己的規則。定義自己的運算,保證可逆數據不丟失即可。key也可定義,動態key。
java代碼
1
2
3
4
5
6
7
8
9
10
11
12
|
public static String myEncode(String str) throws UnsupportedEncodingException { byte [] strBytes = str.getBytes( "utf-8" ); byte [] newStrByte = new byte [strBytes.length]; for ( int i = 0 ; i < strBytes.length; i++) { newStrByte[i] = ( byte ) (strBytes[i] ^ 0x01 ); } return new String(newStrByte); } String encodeStr = myEncode( "IdmmnA\"547''+) ')%\"A ^*((!Vnsme" ); System.out.println(encodeStr); |
獲取utf-8的byte
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
function toUTF8Array(str) { var utf8 = []; for ( var i=0; i < str.length; i++) { var charcode = str.charCodeAt(i); if (charcode < 0x80) utf8.push(charcode); else if (charcode < 0x800) { utf8.push(0xc0 | (charcode >> 6), 0x80 | (charcode & 0x3f)); } else if (charcode < 0xd800 || charcode >= 0xe000) { utf8.push(0xe0 | (charcode >> 12), 0x80 | ((charcode>>6) & 0x3f), 0x80 | (charcode & 0x3f)); } // surrogate pair else { i++; // UTF-16 encodes 0x10000-0x10FFFF by // subtracting 0x10000 and splitting the // 20 bits of 0x0-0xFFFFF into two halves charcode = 0x10000 + (((charcode & 0x3ff)<<10) | (str.charCodeAt(i) & 0x3ff)); utf8.push(0xf0 | (charcode >>18), 0x80 | ((charcode>>12) & 0x3f), 0x80 | ((charcode>>6) & 0x3f), 0x80 | (charcode & 0x3f)); } } return utf8; } |
獲取byte并進行^計算
1
2
3
4
5
6
7
8
9
|
bytes=stringToAsciiByteArray(str); for ( var i = 0; i < bytes.length; i++) { var newByte = (bytes[i]^0x01); // newByte = (newByte^0x01); console.log(String.fromCharCode(newByte)); encodeStr += String.fromCharCode(newByte); }; console.log(encodeStr); |
總結
以上就是本文關于java&javascript自定義加密數據傳輸代碼示例的全部內容,希望對大家有所幫助。如有不足之處,歡迎留言指出。
原文鏈接:http://blog.csdn.net/mendeliangyang/article/details/50108071