java&javascript自定義加密數(shù)據(jù)傳輸代碼示例
在開發(fā)應(yīng)用過程中,客戶端與服務(wù)端經(jīng)常需要進(jìn)行數(shù)據(jù)傳輸,涉及到重要隱私信息時(shí),開發(fā)者自然會(huì)想到對(duì)其進(jìn)行加密,即使傳輸過程中被“有心人”截取,也不會(huì)將信息泄露。對(duì)于加密算法,相信不少開發(fā)者也有所耳聞,比如MD5加密,Base64加密,DES加密,AES加密,RSA加密等等。??衫靡嗷颍?,且,等進(jìn)行簡(jiǎn)單加密。
示例代碼中使用的^運(yùn)算key=0x01,可自定義自己的規(guī)則。定義自己的運(yùn)算,保證可逆數(shù)據(jù)不丟失即可。key也可定義,動(dòng)態(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并進(jìn)行^計(jì)算
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ù)傳輸代碼示例的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站:
Java探索之Thread+IO文件的加密解密代碼實(shí)例
多模字符串匹配算法原理及Java實(shí)現(xiàn)代碼
如有不足之處,歡迎留言指出。
相關(guān)文章
Springmvc數(shù)據(jù)回顯實(shí)現(xiàn)原理實(shí)例解析
這篇文章主要介紹了Springmvc數(shù)據(jù)回顯實(shí)現(xiàn)原理實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09springboot啟動(dòng)后和停止前執(zhí)行方法示例詳解
這篇文章主要介紹了springboot啟動(dòng)后和停止前執(zhí)行方法,本文通過示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-08-08springboot @ComponentScan注解原理解析
這篇文章主要介紹了springboot @ComponentScan注解原理解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02關(guān)于JDK15的新特性之TextBlocks文本塊的引入和使用
這篇文章主要介紹了關(guān)于JDK15的新特性之文本塊的引入和使用,如果具有一種語言學(xué)機(jī)制,可以比多行文字更直觀地表示字符串,而且可以跨越多行,而且不會(huì)出現(xiàn)轉(zhuǎn)義的視覺混亂,那么這將提高廣泛Java類程序的可讀性和可寫性,需要的朋友可以參考下2023-07-07