2013-12-15 68 views
0

你好傢伙我在這個腳本中遇到了一些麻煩。該腳本應該基本上提示輸入,然後加密用戶輸入的任何內容,然後用戶可以通過輸入加密的消息返回並解密該消息。腳本的加密部分工作正常,只是解密部分給我帶來了問題。下面是代碼和ofcourse在此先感謝: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進行編碼,因爲您的加密文本只包含高達127的ASCII字符。