12

我一直在尝试在 Python 中实现 AES CBC 解密。由于密文不是 16 字节的倍数,因此需要填充。没有填充,这个错误浮出水面

“TypeError:奇数长度的字符串”

但是我找不到在 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 
4

1 回答 1

25

您需要在解密之前解码您的十六进制编码值。如果您想使用十六进制编码的密钥,也可以对其进行解码..

在这里,这应该工作。

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
于 2012-12-15T14:49:51.080 回答