Encrypt & Decrypt using PyCrypto AES 256

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

    For someone who would like to use urlsafe_b64encode and urlsafe_b64decode, here are the version that're working for me (after spending some time with the unicode issue)

    BS = 16
    key = hashlib.md5(settings.SECRET_KEY).hexdigest()[:BS]
    pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
    unpad = lambda s : s[:-ord(s[len(s)-1:])]
    
    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.urlsafe_b64encode(iv + cipher.encrypt(raw)) 
    
        def decrypt(self, enc):
            enc = base64.urlsafe_b64decode(enc.encode('utf-8'))
            iv = enc[:BS]
            cipher = AES.new(self.key, AES.MODE_CBC, iv)
            return unpad(cipher.decrypt(enc[BS:]))
    

提交回复
热议问题