Which method encrypts data using AES in Python natively?

What is the best way to perform AES encryption in Python without installing extra modules? Is it possible to encrypt and decrypt data using AES in Python without relying on external libraries? I need to communicate with a system in C#, where the encryption uses the System.Security.Cryptography reference.

Additionally, I attempted to use PyAES, but it seems outdated. While I tried updating some parts of it to make it work, it still failed. I also can’t install certain libraries because my Python version is 3.4, and most latest versions require newer Python versions. Are there alternative solutions for Python AES encryption in this scenario?

Hey @Punamhans

I have been throught your part and you can Use hashlib and os for a Simplified AES-like Implementation as i did the same and it worked for me.

While Python’s standard library does not include a direct implementation of AES, you can approximate encryption by using the hashlib library to create secure hashes and the os library for generating random initialization vectors (IVs). Below is a simplified example:

import hashlib
from os import urandom

def simple_encrypt(key, plaintext):
    # Generate a 16-byte IV
    iv = urandom(16)
    key_hash = hashlib.sha256(key.encode()).digest()[:16]  # Use 16 bytes of the hash
    ciphertext = bytearray(a ^ b for a, b in zip(plaintext.encode(), key_hash))
    return iv + ciphertext  # Concatenate IV with the ciphertext

def simple_decrypt(key, encrypted_data):
    iv = encrypted_data[:16]
    ciphertext = encrypted_data[16:]
    key_hash = hashlib.sha256(key.encode()).digest()[:16]
    plaintext = ''.join(chr(a ^ b) for a, b in zip(ciphertext, key_hash))
    return plaintext

# Example usage
key = "my_secret_key"
plaintext = "Hello, AES!"
encrypted = simple_encrypt(key, plaintext)
decrypted = simple_decrypt(key, encrypted)
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypted}")

This method isn’t a true AES encryption, but it demonstrates how to create a basic encryption mechanism.

@Punamhans There is also a mannual AES Implementation that uses Standard Python

If you cannot install external modules and need to implement AES manually, you can refer to the FIPS-197 AES specification and write the algorithm from scratch.

This will involve implementing key expansion, substitution bytes (S-Box), shift rows, mix columns, and add round key processes.

Here’s a starting point for implementing AES from scratch (showing key expansion logic as an example):

# Example key expansion function for AES
def aes_key_expansion(key):
    rcon = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36]
    expanded_key = [key[i:i+4] for i in range(0, len(key), 4)]
    while len(expanded_key) < 44:  # AES-128 requires 44 words
        temp = expanded_key[-1]
        if len(expanded_key) % 4 == 0:
            temp = [temp[(i + 1) % 4] for i in range(4)]  # Rotate
            temp = [sbox[b] for b in temp]  # Substitute bytes
            temp[0] ^= rcon[len(expanded_key) // 4 - 1]
        expanded_key.append([a ^ b for a, b in zip(expanded_key[-4], temp)])
    return expanded_key

# Implement full AES algorithm based on this foundation

This approach is complex, time-consuming, and error-prone, but it avoids external dependencies entirely.

@charity-majors This seems to be the same way I was using, but I switched to using the cryptography or PyCrypto Library in an Offline Environment

Cause installing external libraries is challenging due to environment restrictions, you could download a standalone .whl file for cryptography or PyCrypto and manually transfer it to the restricted environment. For Python 3.4, compatible versions of these libraries exist.

Steps:

  1. Download a compatible .whl file for your Python version from PyPI or other sources.
  2. Transfer the .whl file to the target environment.
  3. Install it using pip install package-name.whl.

Here’s an example with cryptography (if installed):

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import os

def encrypt(key, plaintext):
    iv = os.urandom(16)
    cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
    encryptor = cipher.encryptor()
    ciphertext = encryptor.update(plaintext) + encryptor.finalize()
    return iv + ciphertext

def decrypt(key, encrypted_data):
    iv = encrypted_data[:16]
    ciphertext = encrypted_data[16:]
    cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
    decryptor = cipher.decryptor()
    return decryptor.update(ciphertext) + decryptor.finalize()

# Example usage
key = b"16byteslongkey!!"
plaintext = b"Hello, AES!"
encrypted = encrypt(key, plaintext)
decrypted = decrypt(key, encrypted)
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypted}")

If possible, try to upgrade Python to access the latest cryptography tools directly.