2013-12-15 2 views
0

Привет, ребята, у меня проблемы с этим скриптом. Предполагается, что сценарий в основном запрашивает ввод, а затем шифрует все, что у пользователя есть, пользователь может вернуться и расшифровать сообщение, введя зашифрованное сообщение. Часть шифрования скрипта работает нормально, это просто часть дешифрования, которая дает мне проблемы. Вот код, и, конечно, заранее спасибо: DРеверсивный алгоритм шифрования в Python

def encrypt(key, msg): 
    encryped = [] 
    for i, c in enumerate(msg): 
     key_c = ord(key[i % len(key)]) 
     msg_c = ord(c) 
     encryped.append(chr((msg_c + key_c) % 127)) 
    return ''.join(encryped) 

def decrypt(key, encryped): 
    msg2 = [] 
    for i, c in enumerate(encryped): 
     key_c = ord(key[i % len(key)]) 
     enc_c = ord(c) 
     msg.append(chr((enc_c - key_c) % 127)) 
    return ''.join(msg) 

welcome = str(input("Press 1 to encrypt or anything else to decrypt: ")) 
if welcome in ['1', '1']: 
    var = input("Please type in what you want to encrypt: ") 
    if __name__ == '__main__': 
     key = 'This is the key' 
     msg = var 
     encrypted = encrypt(key, msg) 
     decrypted = decrypt(key, encrypted) 
    print ('Please take down the key and encryption message to decrypt this message at a later stage') 
    print ('This is what you want to encrypt:' , repr(msg)) 
    print ('This is the encryption/decryption key:', repr(key)) 
    print ('This is the encrypted message:', repr(encrypted)) 

else: 
    var2 = input("Please enter your encrypted message that you would like to decrypt: ") 
    if __name__ == '__main__': 
     key = 'This is the key' 
     msg = var2 
     decrypted = decrypt(key, var2) 
    print ('This is the decrypted message:', repr(decrypted)) 
+0

Не могли бы вы привести пример зашифрованного сообщения? – RageCage

+0

Это то, что «Hello World» выглядит при шифровании: «\ x1dNV'O \ nkO'fD» – AbdulNaji

ответ

0

Немного упрощенная версия:

def encrypt(key, msg): 
    encrypted = [] 
    for i, c in enumerate(msg): 
     key_c = ord(key[i % len(key)]) 
     msg_c = ord(c) 
     encrypted.append(chr((msg_c + key_c) % 127)) 
    return ''.join(encrypted) 

def decrypt(key, encryped): 
    msg = [] 
    for i, c in enumerate(encryped): 
     key_c = ord(key[i % len(key)]) 
     enc_c = ord(c) 
     msg.append(chr((enc_c - key_c) % 127)) 
    return ''.join(msg) 

if __name__ == '__main__': 
    welcome = input('Press 1 to encrypt or anything else to decrypt: ') 
    key = 'This is the key' 
    if welcome == '1': 
     msg = input('Please type in what you want to encrypt: ') 
     encrypted = encrypt(key, msg) 
     print('Please take down the key and encryption message to decrypt this message at a later stage') 
     print('This is what you want to encrypt:', repr(msg)) 
     print('This is the encryption/decryption key:', repr(key)) 
     print('This is the encrypted message:', repr(encrypted)) 
    else: 
     msg = input('Please enter your encrypted message that you would like to decrypt: ') 
     msg = msg.encode('utf-8').decode('unicode_escape') 
     decrypted = decrypt(key, msg) 
     print('This is the decrypted message:', repr(decrypted)) 

Поскольку ваш зашифрованный текст содержит первые 32 ASCII символов, как сбежавшие шестигранных литералы, на входе дешифрования они не интерпретируется как таковой. Для обработки экранированных литералов можно использовать msg.encode("utf-8").decode("unicode_escape") (как предложено here). Вы также можете кодировать с помощью ascii, так как ваш зашифрованный текст содержит только символы ASCII до 127.

Смежные вопросы