java & javascript 自定义加密数据传输
再实际开发中可以能遇到不希望明文传输,简单加密处理的数据。可利用 亦或,并,且,等进行简单加密。
示例代码中使用的 ^ 运算 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);