在開發應用過程中,客戶端與服務端經常需要進行數據傳輸,涉及到重要隱私信息時,開發者自然會想到對其進行加密,即使傳輸過程中被“有心人”截取,也不會將信息泄露。對于加密算法,相信不少開發者也有所耳聞,比如MD5加密,Base64加密,DES加密,AES加密,RSA加密等等。??衫靡嗷?,并,且,等進行簡單加密。
示例代碼中使用的^運算key=0x01,可自定義自己的規則。定義自己的運算,保證可逆數據不丟失即可。key也可定義,動態key。
java代碼
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);
javascript代碼
獲取utf-8的byte
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并進行^計算
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自定義加密數據傳輸代碼示例的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站:
Java探索之Thread+IO文件的加密解密代碼實例
多模字符串匹配算法原理及Java實現代碼
java算法實現紅黑樹完整代碼示例
如有不足之處,歡迎留言指出。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。