2012-09-24 204 views
10

我一直試圖在Python中實現AES CBC解密。由於加密文本不是16字節的倍數,因此填充是必需的。沒有填充,這個錯誤浮出水面使用PKCS5進行AES解密填充Python

「類型錯誤:奇數長度字符串」

但我無法找到在PyCrypto的Python實現PKCS5一個適當的參考。 是否有任何命令來執行此操作? 謝謝

在看着馬庫斯的建議後,我做到了。

我的目標實際上是使用此代碼解密一個十六進制消息(128字節)。但是,輸出是非常小的「?:」,unpad命令正在刪除這些字節。這是代碼。

from Crypto.Cipher import AES 
BS = 16 
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) 
unpad = lambda s : s[0:-ord(s[-1])] 

class AESCipher: 
    def __init__(self, key): 
    self.key = key 

    def encrypt(self, raw): 
     raw = pad(raw) 
     iv = raw[:16] 
     raw=raw[16:] 
     #iv = Random.new().read(AES.block_size) 
     cipher = AES.new(self.key, AES.MODE_CBC, iv) 
     return (iv + cipher.encrypt(raw)).encode("hex") 

    def decrypt(self, enc): 
     iv = enc[:16] 
     enc= enc[16:] 
     cipher = AES.new(self.key, AES.MODE_CBC, iv) 
     return unpad(cipher.decrypt(enc)) 

mode = AES.MODE_CBC 
key = "140b41b22a29beb4061bda66b6747e14" 
ciphertext = "4ca00ff4c898d61e1edbf1800618fb2828a226d160dad07883d04e008a7897ee2e4b7465d5290d0c0e6c6822236e1daafb94ffe0c5da05d9476be028ad7c1d81"; 
key=key[:32] 
decryptor = AESCipher(key) 
decryptor.__init__(key) 
plaintext = decryptor.decrypt(ciphertext) 
print plaintext 
+1

http://stackoverflow.com/questions/12524994/encrypt-decrypt-using-pycrypto-aes-256/12525165#12525165,在回答填充功能可以幫助:) – Marcus

回答

18

您需要在解密之前解碼您的十六進制編碼值。如果你想使用十六進制編碼密鑰,解碼它。以及

在這裏,這應該工作。

from Crypto.Cipher import AES 
from Crypto import Random 

BS = 16 
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) 
unpad = lambda s : s[0:-ord(s[-1])] 

class AESCipher: 
    def __init__(self, key): 
     """ 
     Requires hex encoded param as a key 
     """ 
     self.key = key.decode("hex") 

    def encrypt(self, raw): 
     """ 
     Returns hex encoded encrypted value! 
     """ 
     raw = pad(raw) 
     iv = Random.new().read(AES.block_size); 
     cipher = AES.new(self.key, AES.MODE_CBC, iv) 
     return (iv + cipher.encrypt(raw)).encode("hex") 

    def decrypt(self, enc): 
     """ 
     Requires hex encoded param to decrypt 
     """ 
     enc = enc.decode("hex") 
     iv = enc[:16] 
     enc= enc[16:] 
     cipher = AES.new(self.key, AES.MODE_CBC, iv) 
     return unpad(cipher.decrypt(enc)) 

if __name__== "__main__": 
    key = "140b41b22a29beb4061bda66b6747e14" 
    ciphertext = "4ca00ff4c898d61e1edbf1800618fb2828a226d160dad07883d04e008a7897ee2e4b7465d5290d0c0e6c6822236e1daafb94ffe0c5da05d9476be028ad7c1d81" 
    key=key[:32] 
    decryptor = AESCipher(key) 
    plaintext = decryptor.decrypt(ciphertext) 
    print "%s" % plaintext 
+0

這**,**在'ciphertext = ...'末尾不應該有...... – kravietz

相關問題