异或密码













简单异或密码英语:simple XOR cipher)是密码学中一种简单的加密算法,它按照如下原则进行运算:


A {displaystyle oplus }oplus 0 = A

A {displaystyle oplus }oplus A = 0

(A {displaystyle oplus }oplus B) {displaystyle oplus }oplus C = A {displaystyle oplus }oplus (B {displaystyle oplus }oplus C)

(B {displaystyle oplus }oplus A) {displaystyle oplus }oplus A = B {displaystyle oplus }oplus 0 = B

其中{displaystyle oplus }oplus 为逻辑异或(XOR)运算的符号。按这种逻辑,文本序列的每个字符可以通过与给定的密钥进行按位异或运算来加密。如果要解密,只需要将加密後的结果与密钥再次进行按位异或运算即可。


例如,字符串“Wiki”(8位ASCII:01010111 01101001 01101011 01101001) 可以按如下的方式用密钥11110011进行加密:
















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

此種加密方法類似對稱加密,故解密的方式如下:
















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

异或运算符常作为更为复杂的加密算法的组成部分。对於其本身来说,如果使用不断重复的密钥,利用频率分析就可以破解这种简单的异或密码。如果消息的内容被猜出或知道,密钥就会泄露。异或密码值得使用的原因主要是其易於实现,而且计算成本小。简单重复异或加密有时用於不需要特别安全的情况下来隐藏信息。


如果密钥是随机的(不重复),而且与消息长度相同,异或密码就会更为安全。当密钥流由伪随机数发生器英语pseudo-random number generator生成时,结果就是流密码。若密钥是真正随机的,结果就是一次性密碼本,這種密码在理论上是不可破解的。


在这些密码的任何部分中,密钥运算符在已知明文攻击下都是脆弱的,这是因为明文 {displaystyle oplus }oplus 密文 = 密钥




目录






  • 1 程式碼範例


    • 1.1 C語言


    • 1.2 Python




  • 2 参见


  • 3 外部链接





程式碼範例



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


参见



  • 维尔南密码

  • 维吉尼亚密码



外部链接



  • (英文)Solving the Basic XOR Cipher



Popular posts from this blog

澳門輕軌系統

水泉澳邨

Indian Forest Service