最简单的加密当然是混淆了. 任何一个字节,通过两次异或可以还原, 那么用这个原理就可以双方约定一组约定的字节序列进行混淆了
好了, 直接贴几个语言的实现
第一个luajit
local bit = require 'bit' local function xor_encode(input, key) assert(#key > 0) --为了便于计算,这里使用0开始循环,由于lua语言的差异(末尾是闭区间), 所以减一 local input_count, key_count = #input, #key local ret = '' for i = 1, input_count do local a = string.byte(input, i) local j = i%key_count local e = string.byte(key, j == 0 and key_count or j) local v = bit.bxor(a, e) ret = ret .. string.char(v) end return ret end local t = xor_encode('hello!', 'ab') print(xor_encode(t, 'ab'))
贴个dart版本的
import 'dart:convert' show utf8; // 将字符加密 List<int> xorEncode(String input,String key) { final keyLen = key.length; final count = input.length; List<int> inputBytes = utf8.encode(input); List<int> keyBytes = utf8.encode(key); List<int> ret = []; for(var i=0; i<count; i++){ final j = i%keyLen; final v = inputBytes[i] ^ keyBytes[j]; ret.add(v); } return ret; } // 将加密后的东西解开 String xorDecode(List<int> inputBytes, String key) { List<int> keyBytes = utf8.encode(key); final keyLen = key.length; final count = inputBytes.length; for(var i=0; i<count; i++){ final j = i%keyLen; inputBytes[i] ^= keyBytes[j]; } return utf8.decode(inputBytes); } void main() async { final input = "hello!"; final key = "ab"; final encRet = xorEncode(input, key); final decRet = xorDecode(encRet, key); print(decRet); }
再来个js版本的
// 编码 function xorEncode(input, key) { let len = input.length let keyLen = key.length let results = [] for(var i = 0; i < len; i++) { let j = i%keyLen let v = input[i].charCodeAt() ^ key[j].charCodeAt() results.push(v) } return results } // 解码 function xorDecode(input, key) { let len = input.length let keyLen = key.length let results = '' for(var i = 0; i < len; i++) { let j = i%keyLen let v = input[i] ^ key[j].charCodeAt() results += String.fromCharCode(v) } return results } let e = xorEncode('hello~!', 'ab') console.log(xorDecode(e, 'ab'))