2013-06-27 4 views
0

Это программа, которую я сделал для шифрования текста с использованием одного тайм-кода, но программа неправильно расшифровывает шифрованный текст, некоторые из символов выводятся как вопросительные знаки, я думаю, что проблема связанных с модульной арифметической частью кода.Неполное дешифрование Python

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

Быстрое предположение: возможно, вы захотите выполнить декомпозицию с использованием модульной арифметики: 'lambda x: (x [0] -x [1])% 26' – J0HN

+0

Почему 26, я не использую только алфавит, используя ascii с 256 –

+0

Эх, да, так будет mod 256 быть решением? Кроме того, вы можете захотеть убедиться, что ваши файлы открыты в двоичном режиме. Не все символы '(c + x)% 256' являются допустимым текстовым символом. –

ответ

1

Вы можете выполнить модуль 256 на конечном значении. Вы можете захотеть убедиться, что ваши файлы открыты в двоичном режиме; не все значения (c + x) % 256 приведут к действительным символам.

+0

Спасибо, что решил проблему, и программа теперь работает. –