Encrypt & Decrypt using PyCrypto AES 256

后端 未结 12 895
夕颜
夕颜 2020-11-22 13:07

I\'m trying to build two functions using PyCrypto that accept two parameters: the message and the key, and then encrypt/decrypt the message.

I found several links on

12条回答
  •  盖世英雄少女心
    2020-11-22 13:20

    You may need the following two functions: pad- to pad(when doing encryption) and unpad- to unpad (when doing decryption) when the length of input is not a multiple of BLOCK_SIZE.

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

    So you're asking the length of key? You can use the md5sum of the key rather than use it directly.

    More, according to my little experience of using PyCrypto, the IV is used to mix up the output of a encryption when input is same, so the IV is chosen as a random string, and use it as part of the encryption output, and then use it to decrypt the message.

    And here's my implementation, hope it will be useful for you:

    import base64
    from Crypto.Cipher import AES
    from Crypto import Random
    
    class AESCipher:
        def __init__( self, key ):
            self.key = key
    
        def encrypt( self, raw ):
            raw = pad(raw)
            iv = Random.new().read( AES.block_size )
            cipher = AES.new( self.key, AES.MODE_CBC, iv )
            return base64.b64encode( iv + cipher.encrypt( raw ) ) 
    
        def decrypt( self, enc ):
            enc = base64.b64decode(enc)
            iv = enc[:16]
            cipher = AES.new(self.key, AES.MODE_CBC, iv )
            return unpad(cipher.decrypt( enc[16:] ))
    

提交回复
热议问题