简体   繁体   中英

Efficient method to do AES 256bit encryption in python

I need to encrypt a large file using python. Doing some online research suggested me several modules. I am a bit confused to chose what to use.

I want to make sure that it must work efficiently as much as possible with python.

What is the most efficient python AES 256 encryption module?

You can try ' PyCryptodome ' package that supports AES-NI mode if your hardware supports it. PyCryptodome supports AES encrypion with 256 bits key. You can use GCM mode if you seek for encryption+authentication. If authentication is not in your interest you can use CTR mode.

Code example for CTR mode:

from Crypto.Cipher import AES
# encryption
    cipher = AES.new(key_bytes, AES.MODE_CTR, use_aesni='True')
    ciphertext = cipher.encrypt(data_as_bytes)
    nonce = cipher.nonce
# decryption
    cipher = AES.new(key_bytes, AES.MODE_CTR, nonce=nonce, use_aesni='True')
    plaintext_as_bytes = cipher.decrypt(ciphertext)

Code example for GCM mode:

from Crypto.Cipher import AES
# encryption
    cipher = AES.new(key_bytes, AES.MODE_GCM, use_aesni='True')
    nonce = cipher.nonce
    ciphertext, tag = cipher.encrypt_and_digest(data_as_bytes)
# decryption
    cipher = AES.new(key_bytes, AES.MODE_GCM, nonce=nonce, use_aesni='True')
    plaintext_as_bytes = cipher.decrypt(ciphertext)
    try:
         cipher.verify(tag)
         print("The message is authenticated")
    except ValueError:
         print("Key incorrect or message corrupted")

To check if your hardware supports AES-NI mode you can check the answers here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM