【发布时间】:2021-07-07 03:04:00
【问题描述】:
我正在尝试实现重复键 xor encryption scheme in python。
我有这个实现:
from binascii import hexlify
def repeat_to_length(string_to_expand, length):
return (string_to_expand * (int(length/len(string_to_expand))+1))[:length]
def Enc(plaintext,k):
ciphertext = b''
s1 = str.encode(plaintext)
key = str.encode(repeat_to_length(k, len(s1)))
i = 0
for s11,k1 in zip(s1,key):
tmp = bytes(s11^k1)
ciphertext += tmp
return ciphertext
key = "ICE"
m1 = "Burning 'em, if you ain't quick and nimble"
m2 = "I go crazy when I hear a cymbal"
c = Enc(m1,key)
print(str(hexlify(c), "utf-8"))
我使用函数repeat_to_length将密钥长度扩展为与明文相同的长度,只是为了方便使用。然后我将这两个字符串转换为字节对象,以便我能够对它们进行异或。
这里奇怪的是,当我在这里运行我的代码时,这是我得到的输出:
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
发生了什么?为什么异或只渲染为零?
【问题讨论】:
-
仅供参考,
itertools.cycle()是一种根据需要重复密钥的更简单方法。 -
bytes(n)不会将n转换为一个字节,它会创建一个bytes带有n零的对象。