Encrypt file in python with aes

12,429

A quick Google search guided me to the Crypto package. It comes with the iPython that I am using, but the installation should be trivial anyway.

I just repost the example here for your information.

>>> from Crypto.Cipher import AES
>>> obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
>>> message = "The answer is no"
>>> ciphertext = obj.encrypt(message)
>>> ciphertext
'\xd6\x83\x8dd!VT\x92\xaa`A\x05\xe0\x9b\x8b\xf1'
>>> obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
>>> obj2.decrypt(ciphertext)
'The answer is no'

Here is the documentation of AES.

If you try to encrypt file, you can either use the openSSL or a Python solution using Crypto contributed by Thijs. Click here for more information.

Share:
12,429
idk
Author by

idk

Updated on June 04, 2022

Comments

  • idk
    idk almost 2 years

    I want to encrypt and decrypt a file (any type of file) using aes 128 in cbc mode in python.

    I am quite new to cryptography and i have tried some tutorials but all work only on texts, and i need it for files.

    Could anyone suggest me a solution?

  • jlh
    jlh about 3 years
    Be aware that this library has been abandoned for years.