异或密码

C语言

加密：
 while (done < len) {
        tmp_ch = *buffer;
        for(int i = 0; i < key_len; i++)
                tmp_ch ^= key[i];
        *crypted = tmp_ch;
        crypted++; buffer++; done++;
 }
解密：
 while (done <= len) {
        tmp_ch = *buffer;
        for(int i = key_len-1; i >= 0; i--)
                tmp_ch ^= key[i];
        *decrypted = tmp_ch;
        decrypted++; buffer++; done++;
 }

Python

#!/usr/bin/env pythonfrom __future__ import print_functionfrom os import urandomdef o(x): # Python 2 and 3 compatibility with bytes
    if isinstance(x, str):
        return ord(x)
    else:
        return xdef genkey(length):
    """Generate key"""
    return urandom(length)def xor_strings(s,t):
    """xor two strings together"""
    return "".join(chr(o(a)^o(b)) for a,b in zip(s,t))message = 'This is a secret message'print('message:', message)key = genkey(len(message))print('key:', key)cipherText = xor_strings(message, key)print('cipherText:', cipherText)print('decrypted:', xor_strings(cipherText,key))# verifyif xor_strings(cipherText, key) == message:
    print('Unit test passed')else:
    print('Unit test failed')