java&javascript自定義加密數(shù)據(jù)傳輸代碼示例
在開發(fā)應(yīng)用過程中,客戶端與服務(wù)端經(jīng)常需要進行數(shù)據(jù)傳輸,涉及到重要隱私信息時,開發(fā)者自然會想到對其進行加密,即使傳輸過程中被“有心人”截取,也不會將信息泄露。對于加密算法,相信不少開發(fā)者也有所耳聞,比如MD5加密,Base64加密,DES加密,AES加密,RSA加密等等。??衫靡嗷颍?,且,等進行簡單加密。
示例代碼中使用的^運算key=0x01,可自定義自己的規(guī)則。定義自己的運算,保證可逆數(shù)據(jù)不丟失即可。key也可定義,動態(tài)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);
總結(jié)
以上就是本文關(guān)于java&javascript自定義加密數(shù)據(jù)傳輸代碼示例的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站:
如有不足之處,歡迎留言指出。
相關(guān)文章
spring mvc中的@PathVariable動態(tài)參數(shù)詳解
這篇文章主要介紹了spring mvc中的@PathVariable動態(tài)參數(shù)詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
mybatis@insert?注解如何判斷insert或是update
這篇文章主要介紹了mybatis@insert?注解如何判斷insert或是update,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07
springboot整合mybatis實現(xiàn)多表查詢的實戰(zhàn)記錄
SpringBoot對數(shù)據(jù)庫操作有多種方式,下面這篇文章主要給大家介紹了關(guān)于springboot整合mybatis實現(xiàn)多表查詢的相關(guān)資料,文中通過示例代碼以及圖文介紹的非常詳細(xì),需要的朋友可以參考下2021-08-08

