Home  >  Article  >  Backend Development  >  How to Implement Secure AES-256 Encryption and Decryption in Python?

How to Implement Secure AES-256 Encryption and Decryption in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-21 07:17:09154browse

How to Implement Secure AES-256 Encryption and Decryption in Python?

Encrypting and Decrypting with PyCrypto AES-256

To construct efficient encrypting and decrypting functions using PyCrypto that operate on a message and a key, certain considerations must be taken into account.

Key Alignment and Entropy:

It's crucial to ensure that the provided key has the expected length. PyCrypto suggests using a strong key with a length of 32 bytes. To achieve this, hash the key with SHA-256 and use the resulting digest as the encryption key.

Encryption Modes:

For AES encryption, Cipher Block Chaining (CBC) mode is commonly used. It provides added security by combining successive blocks of ciphertext with an Initialization Vector (IV).

Initialization Vector (IV):

The IV is a random value that is prepended to the ciphertext during encryption. It ensures the uniqueness of each encrypted message and prevents attackers from utilizing patterns within the ciphertext. You can supply different IVs for encryption and decryption, but it's essential to use a unique IV for each encryption operation.

Implementation:

The sample implementation below incorporates these considerations:

import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES

class AESCipher(object):

    def __init__(self, key):
        self.bs = AES.block_size
        self.key = hashlib.sha256(key.encode()).digest()

    def encrypt(self, raw):
        raw = self._pad(raw)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(raw.encode()))

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        iv = enc[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return AESCipher._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')

    def _pad(self, s):
        return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)

    @staticmethod
    def _unpad(s):
        return s[:-ord(s[len(s)-1:])]

This implementation ensures that the key is securely hashed to 32 bytes, uses CBC mode for encryption, and generates a random IV during encryption. The decryption function recovers the IV from the ciphertext and uses it to reverse the encryption process.

The above is the detailed content of How to Implement Secure AES-256 Encryption and Decryption in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn