1

I am working on an app that needs to encrypt / decrypt data coming from and going to client app coded in AS3 (yeah I know...) that use this lib http://crypto.hurlant.com/

I found many threads here or there about AES encryption with Python but for some reason I wasn't able to use them in my case.

My encrypted data is AES 256 bits CBC PKCS#5 then Base64 encoded and transmitted via web socket to Python.

Example of data generated by client app :

key : fce4aa4dcf0d2b27fe4ffdafa602c81d1930c410f48ada5c763d4c4052a939eb

IV : c75271d593ca86ca785e3bb25e8d02cb

clear data : This bloody encryption engine won't work !

encrypted data : 44FsQIcqM412+YXZBwwoQSCz2uB9QPQMXJ410Xpw1f/M5RTRS7N6yfziAGq/Fd/E

I tried using the code on this thread Encrypt & Decrypt using PyCrypto AES 256 but there are so many example with different settings that I don't know which one to choose, and I am really a noob with encryption. Any help on this ?

Community
  • 1
  • 1
Catmembert
  • 25
  • 1
  • 3

1 Answers1

3

The following code does what you want. It is basically the highest voted answer of your linked question with the IV set externally.

Python 2.x code (if you want Python 3. x code you have to do the Hex decoding differently):

import base64
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[:-ord(s[len(s)-1:])]

class AESCipher:
    def __init__( self, key ):
        self.key = key

    def encrypt( self, raw, iv ):
        raw = pad(raw)
        cipher = AES.new( self.key, AES.MODE_CBC, iv )
        return base64.b64encode( cipher.encrypt( raw ) )

    def decrypt( self, enc, iv ):
        enc = base64.b64decode(enc)
        cipher = AES.new(self.key, AES.MODE_CBC, iv )
        return unpad(cipher.decrypt( enc ))

a = AESCipher('fce4aa4dcf0d2b27fe4ffdafa602c81d1930c410f48ada5c763d4c4052a939eb'.decode('hex_codec'))
print a.encrypt("This bloody encryption engine won't work !", 'c75271d593ca86ca785e3bb25e8d02cb'.decode('hex_codec'))

b = AESCipher('fce4aa4dcf0d2b27fe4ffdafa602c81d1930c410f48ada5c763d4c4052a939eb'.decode('hex_codec'))
print b.decrypt('44FsQIcqM412+YXZBwwoQSCz2uB9QPQMXJ410Xpw1f/M5RTRS7N6yfziAGq/Fd/E', 'c75271d593ca86ca785e3bb25e8d02cb'.decode('hex_codec'))

Output

44FsQIcqM412+YXZBwwoQSCz2uB9QPQMXJ410Xpw1f/M5RTRS7N6yfziAGq/Fd/E
This bloody encryption engine won't work !

The IV must be unpredictable (read: random). Don't use a static IV, because that makes the cipher deterministic and therefore not semantically secure. An attacker who observes ciphertexts can determine when the same message prefix was sent before. The IV is not secret, so you can send it along with the ciphertext. Usually, it is simply prepended to the ciphertext and sliced off before decryption.

Community
  • 1
  • 1
Artjom B.
  • 61,146
  • 24
  • 125
  • 222