Python AES encryption without extra module

Anton picture Anton · Aug 12, 2014 · Viewed 36.4k times · Source

Is it possible to encrypt/decrypt data with AES without installing extra modules? I need to send/receive data from C#, which is encrypted with the System.Security.Cryptography reference.

UPDATE I have tried to use PyAES, but that is too old. I updated some things to make that work, but it didn't. I've also can't install because it latest version is 3.3 while my version is 3.4.

Answer

Vlad Bezden picture Vlad Bezden · Mar 27, 2018

I'm using Cryptography library.

Cryptography is an actively developed library that provides cryptographic recipes and primitives. It supports Python 2.6-2.7, Python 3.3+ and PyPy.

Here is an example of how to use that library:

>>> import os
>>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
>>> from cryptography.hazmat.backends import default_backend
>>> backend = default_backend()
>>> key = os.urandom(32)
>>> iv = os.urandom(16)
>>> cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
>>> encryptor = cipher.encryptor()
>>> ct = encryptor.update(b"a secret message") + encryptor.finalize()
>>> decryptor = cipher.decryptor()
>>> decryptor.update(ct) + decryptor.finalize()
'a secret message'