互斥或密碼

本頁使用了標題或全文手工轉換
維基百科,自由的百科全書

簡單互斥或密碼(英語:simple XOR cipher)是密碼學中一種簡單的加密演算法,它按照如下原則進行運算:

A 0 = A
A A = 0
(A B) C = A (B C)
(B A) A = B 0 = B

其中邏輯互斥或(XOR)運算的符號。按這種邏輯,文字序列的每個字元可以通過與給定的金鑰進行按位元互斥或運算來加密。如果要解密,只需要將加密後的結果與金鑰再次進行按位元互斥或運算即可。

例如,字串「Wiki」(8位元ASCII:01010111 01101001 01101011 01101001) 可以按如下的方式用金鑰11110011進行加密:

01010111 01101001 01101011 01101001
11110011 11110011 11110011 11110011
= 10100100 10011010 10011000 10011010

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

10100100 10011010 10011000 10011010
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')

參見[編輯]

外部連結[編輯]