我最近在与Project Euler Problem 59一起玩之后开始使用加密技术,并且我制作了一个基本的XOR加密系统。在这种情况下,您的输出和随机密钥的连接将被创建并保存到文本文件中(仅作为测试,我会在我修复此错误后使其更好),但我已经注意到了某些邮件不会正确加密或解密。我已将其缩小到长度为>的消息。 54.我的代码如下:
#encrypt.py
import random
msg = raw_input("Enter your message: ")
out = ""
key = ""
for i in xrange(len(msg)):
key += chr(random.randint(0,255))
k = 0
for char in msg:
out += chr(ord(msg[k]) ^ ord(key[k]))
k += 1
print "\nYour output is:", out
print "Your key is:", key
raw_input()
with open("output.txt","r+") as f:
f.truncate()
f.write(out+key)
解密:
#decrypt.py
import sys
if not len(sys.argv) > 1: exit()
with open(sys.argv[1],"r+") as f:
content = f.read()
msg, key = content[:len(content)/2], content[len(content)/2:]
out = ""
k = 0
for char in msg:
out += chr(ord(char) ^ ord(key[k]))
k += 1
print out
raw_input()
对于较长的消息(超过54个字符),当它们被解密时,它们将给出一串随机字符。有没有人知道为什么会这样?
答案 0 :(得分:0)
由于使用随机位制作字符可能会在屏幕上产生看起来很难看的字符,因此您可以在打印前尝试对输出进行十六进制编码。
#encrypt.py
import random
msg = raw_input("Enter your message: ")
out = ""
key = ""
for i in xrange(len(msg)):
key += chr(random.randint(0,255))
k = 0
for char in msg:
out += chr(ord(msg[k]) ^ ord(key[k]))
k += 1
out = ":".join("{:02x}".format(ord(c)) for c in out)
key = ":".join("{:02x}".format(ord(c)) for c in key)
print "\nYour output is:", out
print "Your key is:", key
raw_input()
with open("output.txt","w+") as f:
f.truncate()
f.write(out+key)
然后,对于解密,您必须先删除冒号和十六进制解码才能继续进行常规解密。
#decrypt.py
import sys
if not len(sys.argv) > 1: exit()
with open(sys.argv[1],"r+") as f:
content = f.read()
content = content.replace(':', '')
msg, key = content[:len(content)/2], content[len(content)/2:]
msg = msg.decode('hex')
key = key.decode('hex')
out = ""
k = 0
for char in msg:
out += chr(ord(char) ^ ord(key[k]))
k += 1
print out
raw_input()
在控制台上,结果如下所示:
$ python encrypt.py
Enter your message: onetwothreefourfivesixseveneightnineteneleventwelvethirteen
Your output is: 7f:09:d0:8c:2e:1a:e0:a0:84:e7:bf:3b:e8:cc:f3:4e:35:e4:4f:20:c8:00:72:9d:f0:bc:de:54:88:30:a6:3d:93:3f:c1:6d:46:4a:68:ca:96:2e:16:50:43:0f:30:fa:27:f3:f2:8d:35:4b:6a:11:cc:02:04
Your key is: 10:67:b5:f8:59:75:94:c8:f6:82:da:5d:87:b9:81:28:5c:92:2a:53:a1:78:01:f8:86:d9:b0:31:e1:57:ce:49:fd:56:af:08:32:2f:06:af:fa:4b:60:35:2d:7b:47:9f:4b:85:97:f9:5d:22:18:65:a9:67:6a
$ cat output.txt
7f:09:d0:8c:2e:1a:e0:a0:84:e7:bf:3b:e8:cc:f3:4e:35:e4:4f:20:c8:00:72:9d:f0:bc:de:54:88:30:a6:3d:93:3f:c1:6d:46:4a:68:ca:96:2e:16:50:43:0f:30:fa:27:f3:f2:8d:35:4b:6a:11:cc:02:0410:67:b5:f8:59:75:94:c8:f6:82:da:5d:87:b9:81:28:5c:92:2a:53:a1:78:01:f8:86:d9:b0:31:e1:57:ce:49:fd:56:af:08:32:2f:06:af:fa:4b:60:35:2d:7b:47:9f:4b:85:97:f9:5d:22:18:65:a9:67:6a
$ python decrypt.py output.txt
onetwothreefourfivesixseveneightnineteneleventwelvethirteen