Encrypt & Decrypt using PyCrypto AES 256

后端 未结 12 1092
夕颜
夕颜 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:11

    Another take on this (heavily derived from solutions above) but

    • uses null for padding
    • does not use lambda (never been a fan)
    • tested with python 2.7 and 3.6.5

      #!/usr/bin/python2.7
      # you'll have to adjust for your setup, e.g., #!/usr/bin/python3
      
      
      import base64, re
      from Crypto.Cipher import AES
      from Crypto import Random
      from django.conf import settings
      
      class AESCipher:
          """
            Usage:
            aes = AESCipher( settings.SECRET_KEY[:16], 32)
            encryp_msg = aes.encrypt( 'ppppppppppppppppppppppppppppppppppppppppppppppppppppppp' )
            msg = aes.decrypt( encryp_msg )
            print("'{}'".format(msg))
          """
          def __init__(self, key, blk_sz):
              self.key = key
              self.blk_sz = blk_sz
      
          def encrypt( self, raw ):
              if raw is None or len(raw) == 0:
                  raise NameError("No value given to encrypt")
              raw = raw + '\0' * (self.blk_sz - len(raw) % self.blk_sz)
              raw = raw.encode('utf-8')
              iv = Random.new().read( AES.block_size )
              cipher = AES.new( self.key.encode('utf-8'), AES.MODE_CBC, iv )
              return base64.b64encode( iv + cipher.encrypt( raw ) ).decode('utf-8')
      
          def decrypt( self, enc ):
              if enc is None or len(enc) == 0:
                  raise NameError("No value given to decrypt")
              enc = base64.b64decode(enc)
              iv = enc[:16]
              cipher = AES.new(self.key.encode('utf-8'), AES.MODE_CBC, iv )
              return re.sub(b'\x00*$', b'', cipher.decrypt( enc[16:])).decode('utf-8')
      

提交回复
热议问题