Trouble with encode + encrypt + pad using same code for python2 and python3

前端 未结 4 2073
渐次进展
渐次进展 2021-01-19 04:07

Disclaimer: I understand that the following is not suited to give "security" in a production environment. It is simply meant as "a little bit

4条回答
  •  一向
    一向 (楼主)
    2021-01-19 04:19

    More of an addendum: as result of the answers I got; and digging into AES encryption a bit deeper I figured that the Cipher AES API actually allows for "unpadded" input. I rewrote my code to:

    from __future__ import print_function
    from Crypto.Cipher import AES
    from Crypto.Util import Counter
    
    from base64 import b64decode, b64encode
    
    def scramble(data):
        crypto = AES.new('This is a key123', AES.MODE_CTR, 'This is an IV456', counter=Counter.new(128))
        return b64encode(crypto.encrypt(data))
    
    
    def unscramble(data):
        crypto = AES.new('This is a key123', AES.MODE_CTR, 'This is an IV456', counter=Counter.new(128))
        return crypto.decrypt(b64decode(data))
    
    
    incoming = "123456801DEF"
    print("in: {}".format(incoming))
    scrambled = scramble(incoming)
    print("scrambled: {}".format(scrambled))
    andback = unscramble(scrambled)
    print("reversed : {}".format(andback))
    

    And now I receive the expected results!

    The trick is that I can't reuse the AES object; so a new one needs to be created; and in addition to that AES also offers the CTR mode - and that one does padding internally!

提交回复
热议问题