2015-12-23 32 views
-3

好了,所以這裏是到目前爲止我的代碼:而在Python使用lambda屬性錯誤

import os 
import time 
import random 
import Crypto 
from Crypto.PublicKey import RSA 
from Crypto import Random 
from Crypto.Cipher import AES 
import base64 

key = 'MIICWwIBAAKBgQDN' 
print('do you have a encrypted string in a file?') 
fileexist = input('if so then input 1:') 
if fileexist == 1: 
    filename = raw_input('please input path to file:') 
    file = open(filename,'r') 
    encoded = file.read() 
    type = type(encoded) 
else: 
    encoded = raw_input('please enter encrypted text') 
encoded = str(encoded) 
BLOCK_SIZE = 16 
PADDING = '{' 
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING 
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING) 
decoded = DecodeAES(key, encoded) 
print(decoded) 

我一直線歌廳一個屬性錯誤24我確切的錯誤信息是波紋管

AttributeError: 'str' object has no attribute 'decrpt' 

我我試圖用AES解密一條消息。使用幾乎完全相同的語法,我的加密器工作得很好。我沒有完全理解錯誤的原因。我知道這是可能的,我已經看到其他職位使用這種語法。設置

+3

看起來你的代碼中有一個錯字,或者錯誤信息是你正在嘗試'刪除'你的字符串。檢查你的拼寫? – bcc32

+0

我要離開這段代碼:http://www.codekoala.com/posts/aes-encryption-python-using-pycrypto/本身它可以正常編輯,但是當我將lambda行粘貼到我的代碼中時它錯誤了。我不知道什麼? – MathMXC

+0

鍵只是您的代碼中的一個字符串,它沒有解密方法。你是否打算設置'key = AES.new('MIICWwIBAAKBgQDN')'而不是? – bcc32

回答

1

拼寫問題放在一邊,在您鏈接到代碼中,第一個參數DecodeAESAES.new創建一個AES.AESCipher對象:

# create a cipher object using the random secret 
cipher = AES.new(secret) 

在自己的代碼要傳遞的字符串key,這沒有按」沒有decrypt方法。

而且FWIW這無關與功能被定義爲一個lambda - 功能版本將表現非常相同的方式:

def DecodeAES(c, e): 
    return c.decrypt(base64.b64decode(e)).rstrip(PADDING) 


DecodeAES("foo", "bar") 

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 2, in DecodeAES 
AttributeError: 'str' object has no attribute 'decrypt' 
+0

好的,謝謝。這是我第一次使用lambda,我認爲我在使用它的時候發生了錯誤。非常感謝 – MathMXC

1

您首先需要創建一個AES對象DecodeAES通過。

做它用

key = 'MIICWwIBAAKBgQDN' 
cipher = AES.new(key) 

現在不是在key調用DecodeAES,你怎麼稱呼它,我們與key創建的cipher對象:

decoded = DecodeAES(cipher, encoded) 

這應該使你的代碼工作。