# 异或密码

A ${\displaystyle \oplus }$ 0 = A
A ${\displaystyle \oplus }$ A = 0
(A ${\displaystyle \oplus }$ B) ${\displaystyle \oplus }$ C = A ${\displaystyle \oplus }$ (B ${\displaystyle \oplus }$ C)
(B ${\displaystyle \oplus }$ A) ${\displaystyle \oplus }$ A = B ${\displaystyle \oplus }$ 0 = B

 01010111 01101001 01101011 01101001 ${\displaystyle \oplus }$ 11110011 11110011 11110011 11110011 = 10100100 10011010 10011000 10011010

 10100100 10011010 10011000 10011010 ${\displaystyle \oplus }$ 11110011 11110011 11110011 11110011 = 01010111 01101001 01101011 01101001

## 程式码范例

### 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++;
}
```

### golang

```func XOR(input []byte, key []byte) []byte { //解密時僅需將原本的output改到input,key不變即可
output := make([]byte, len(input))
for i := range input {
output[i] = input[i] ^ key[i%len(key)] //當input比key長時會不斷使用key對每一個byte加密
}
return output
}
```

### Python

```#!/usr/bin/env python

from __future__ import print_function
from os import urandom

def o(x): # Python 2 and 3 compatibility with bytes
if isinstance(x, str):
return ord(x)
else:
return x

def 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))

# verify
if xor_strings(cipherText, key) == message:
print('Unit test passed')
else:
print('Unit test failed')
```