这是我使用一次性密码加密来加密文本的程序,但程序没有正确解密密文,一些字符作为问号输出,我认为问题与模块化算术部分的代码。
import os
#This will open a file for encryption
o = open('/Users/kyle/Desktop/one-time.txt', 'r')
#This is the plain text to encrypt
plain = 'The quick brown fox jumps over the lazy dog'
print 50*"-"
print plain
#This will measure the length of the plain text
f3 = len(plain)
#generate random chacters as long as the text
a1 = os.urandom(f3)
#makes the random characters tuple format
b = list(a1)
b2 = list(plain)
s = plain
#gives the ascii value of the charters
L = [ord(c) for c in s]
print 50*"-"
s = a1
a = [ord(c) for c in s]
b = [ord(c) for c in plain]
#adds the random digits and the plain text
c = map(sum, zip(a,b))
print c
print 50*"-"
#uses Modular arithmetic if the sum is greater than 256 by subtracting 256
x=c
z = []
for y in x:
z.append(y-256 if y>=256 else y)
z = [y-256 if y >= 256 else y for y in x]
print z
#converts the sum back to charter form
cipher_text = ''.join(chr(i) for i in z)
#makes a folder for the files
if os.path.exists("/Users/kyle/one time pad/"):
print
else:
os.mkdir("/Users/kyle/one time pad/")
#makes a file containg the plain text
if os.path.exists("/Users/kyle/one time pad/plain text.txt"):
f = file("/Users/kyle/one time pad/plain text.txt", "w")
f1 = open("/Users/kyle/one time pad/plain text.txt", "w")
f1.write(plain)
f1.close()
else:
f = file("/Users/kyle/one time pad/plain text.txt", "w")
f1 = open("/Users/kyle/one time pad/plain text.txt", "w")
f1.write(plain)
f1.close()
key = a1
#makes a file containg the key
if os.path.exists("/Users/kyle/one time pad/key"):
f1 = file("/Users/kyle/one time pad/key.txt", "w")
f1 = open("/Users/kyle/one time pad/key.txt", "w")
f1.write(key)
f1.close()
else:
f1 = file("/Users/kyle/one time pad/key.txt", "w")
f1 = open("/Users/kyle/one time pad/key.txt", "w")
f1.write(key)
f1.close()
#makes a file containg the cipher text
if os.path.exists("/Users/kyle/one time pad/cipher text.txt"):
f1 = file("/Users/kyle/one time pad/cipher text.txt", "w")
f1 = open("/Users/kyle/one time pad/cipher text.txt", "w")
f1.write(cipher_text)
f1.close()
else:
f1 = file("/Users/kyle/one time pad/cipher text.txt", "w")
f1 = open("/Users/kyle/one time pad/cipher text.txt", "w")
f1.write(cipher_text)
f1.close()
print 50*"-"
这是解密密文的代码。 我认为从密文中减去密钥可能存在问题。
#opens the cipher text and it converts it to decimal
cipher1 = open("/Users/kyle/one time pad/cipher text.txt", "r")
cipher2 = cipher1.read()
cipher3 = [ord(c) for c in cipher2]
#opens the key and coverts it to decimal
key1 = open("/Users/kyle/one time pad/key.txt", "r")
key2 = key1.read()
key3 = [ord(c) for c in key2]
#subtracts the key from the cipher
b = cipher3
a = key3
c = map(lambda x: x[0]-x[1], zip(a,b))
#prints out the decrypted plain text
c1 = [abs(d) for d in c]
print ''.join(map(chr,c1))
答案 0 :(得分:1)
您可以对最终值执行模数256。您可能希望确保以二进制模式打开文件;并非所有(c + x) % 256
值都会产生有效字符。