[英]XOR Cipher in Python: Two Methods With Two Results?
最近,我一直在探索Python中的XOR密碼。 我有兩種“工作”方法:
def XORcipher(plaintext, key):
output = ""
for character in plaintext:
for letter in key:
character = chr(ord(character) ^ ord(letter))
output += character
return output
和
def XORcipher2(plaintext, key):
from itertools import izip, cycle
return ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(plaintext, cycle(key)))
兩者都能夠加密給定的字符串並解密回來。 我似乎無法理解的是為什么它們會給出不同的結果。
使用23
作為我的鑰匙:
XORcipher = Usx!un!dobsxqu!uihr!ldrr`fd!trhof!YNS!dobsxquhno /
和
XORcipher2 = fAKF \\ V \\ P @ JBGGZZA_VA @ STWG @ [] Uj |`W] QAKCFZ]]
如果有人可以幫助我更好地理解這些結果,我將不勝感激!
對於第一個功能,始終使用鍵中的最后一個字符。 這是因為每次迭代時,它都會在for循環中分配給character
,並丟棄最后一個字符,直到您迭代到最后為止。
對於第二個,采用純文本"abc"
和鍵"42"
。 "a"
用"4"
加密。 在使用cycle()
,再次將"b"
與"2"
和"c"
與"4"
一起使用,因此它可以返回到開頭。
與所述第一功能,它是"a"
與"2"
, "b"
與"2"
和"c"
與"2"
。
為了擴展列表理解,應該是這樣的:
from itertools import izip, cycle
def list_comp(plaintext, key):
return ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(plaintext, cycle(key)))
def not_list_comp(plaintext, key):
temp = []
for x, y in izip(plaintext, cycle(key)):
temp.append(chr(ord(x) ^ ord(y)))
return ''.join(temp)
在第一種情況下,對於明文的每個字母,您要對鍵的每個字符執行異或運算。 如果執行XORcipher2('foo', 'bar')
則序列為:
chr(ord('f') ^ ord('b')) # '\x04'
chr(ord('\x04') ^ ord('a')) # ´e´
chr(ord('e') ^ ord('r')) # '\x17'
output += '\x17'
chr(ord('o') ^ ord('b')) # '\r'
chr(ord('\r') ^ ord('a')) # 'e'
chr(ord('l') ^ ord('r')) # '\x1e'
output += '\x1e'
chr(ord('o') ^ ord('b'))
chr(ord('\r') ^ ord('a'))
chr(ord('l') ^ ord('r'))
output += '\x1e'
可能您真正想要的是(假設您希望使用itertools
替代算法):
def XORcipher(plaintext, key):
output = ""
for i, character in enumerate(plaintext):
output += chr(ord(character) ^ ord(key[i % len(key)]))
return output
證明:
>>> XORcipher('foo', 'bar')
'\x04\x0e\x1d'
>>> XORcipher2('foo', 'bar')
'\x04\x0e\x1d'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.