DEV Community

Ethan Callahan
Ethan Callahan

Posted on

Implementing AES Encryption in Python for an Assignment

Data security has become an essential part of modern computing. Applications regularly store and transmit sensitive information such as passwords, personal records, financial information, business documents, and private messages. If this information is stored or transmitted without proper protection, unauthorized individuals may be able to access it.

Encryption is one of the fundamental techniques used to protect sensitive information. Encryption converts readable information, called plaintext, into an unreadable form called ciphertext. Only someone with the appropriate key and cryptographic process should be able to recover the original information.

The Advanced Encryption Standard, commonly known as AES, is one of the most widely used symmetric encryption standards. It is used in many applications and security systems because it provides strong encryption while remaining efficient for modern computers.

Python provides several cryptographic libraries that allow developers to implement AES based encryption without manually implementing the complex mathematical operations behind the algorithm. For an academic assignment, implementing AES in Python provides an excellent opportunity to understand symmetric encryption, keys, initialization vectors, encryption modes, authentication, secure key handling, and decryption.

This assignment explains AES encryption, its working principle, AES key sizes, encryption modes, Python implementation, testing, security considerations, common mistakes, project structure, applications, advantages, limitations, and future scope.

What Is Encryption

Encryption is the process of converting readable data into a protected representation using a cryptographic algorithm and a key.

The original readable information is called plaintext.

After encryption, it becomes ciphertext.

The general process can be represented as

Plaintext
    ↓
Encryption Algorithm + Secret Key
    ↓
Ciphertext
    ↓
Decryption Algorithm + Secret Key
    ↓
Plaintext
Enter fullscreen mode Exit fullscreen mode

For example, a message such as

Hello World
Enter fullscreen mode Exit fullscreen mode

can be transformed into ciphertext that does not resemble the original message.

The exact ciphertext depends on the encryption algorithm, key, mode, and other cryptographic parameters.

Symmetric Encryption

AES belongs to the category of symmetric encryption.

In symmetric encryption, the same secret key is used for encryption and decryption.

              Secret Key
                  ↓
Plaintext → Encryption → Ciphertext
                              ↓
                         Decryption
                              ↓
                           Plaintext
                  ↑
              Secret Key
Enter fullscreen mode Exit fullscreen mode

The sender and receiver must therefore have access to the appropriate secret key.

Symmetric encryption is generally efficient and suitable for protecting large amounts of data.

What Is AES

AES stands for Advanced Encryption Standard.

It is a symmetric block cipher designed to protect digital information.

AES operates on fixed size blocks of data and supports three standard key lengths.

AES Version Key Size Number of Rounds
AES 128 128 bits 10
AES 192 192 bits 12
AES 256 256 bits 14

AES always operates on a block size of 128 bits, regardless of whether the key is 128, 192, or 256 bits.

AES 256 is commonly discussed when stronger key length is desired, while AES 128 can also provide a very strong security level when implemented correctly.

Why AES Is Used

AES is widely used because it provides several important properties.

Strong Security

AES is designed to resist practical cryptanalytic attacks when used correctly.

Efficient Performance

AES can encrypt data efficiently on modern hardware.

Standardization

AES is an established cryptographic standard.

Multiple Key Sizes

Applications can select between 128, 192, and 256 bit keys according to their security requirements.

Wide Adoption

AES is used across many areas of computing and information security.

How AES Works

AES is a block cipher.

It processes data in blocks of 128 bits.

The internal AES process uses several transformation steps.

Important AES operations include

• SubBytes

• ShiftRows

• MixColumns

• AddRoundKey

The exact sequence depends on the AES round and key size.

SubBytes

SubBytes replaces bytes using a predefined substitution table called the S Box.

This transformation introduces nonlinearity into the encryption process.

The substitution contributes to the security properties of AES.

ShiftRows

ShiftRows rearranges the bytes within the AES state.

Different rows are shifted by different amounts.

This helps distribute information across the state.

MixColumns

MixColumns transforms the data within each column of the AES state.

It combines bytes mathematically to create diffusion.

This operation is applied during most AES rounds but is omitted from the final round.

AddRoundKey

AddRoundKey combines the current AES state with a round key derived from the original secret key.

This operation uses XOR at the byte level.

The encryption process therefore combines substitution, permutation, diffusion, and key dependent transformations.

AES Key Sizes

AES supports three standard key sizes.

AES 128

AES 128 uses a 128 bit key and performs 10 rounds.

It offers strong security and can be efficient for many applications.

AES 192

AES 192 uses a 192 bit key and performs 12 rounds.

AES 256

AES 256 uses a 256 bit key and performs 14 rounds.

The larger key does not mean that AES 256 automatically provides better security for every situation. Secure implementation, key management, authentication, and correct cryptographic mode selection are also extremely important.

AES Encryption Modes

AES alone defines the block cipher, but a mode of operation determines how AES is applied to larger amounts of data.

Common modes include

• ECB

• CBC

• CTR

• GCM

Different modes provide different security properties.

ECB Mode

Electronic Codebook mode encrypts each block independently.

It is generally unsuitable for protecting structured data because identical plaintext blocks can produce identical ciphertext blocks when encrypted under the same key.

Therefore, ECB should generally be avoided for normal application encryption.

CBC Mode

Cipher Block Chaining connects each plaintext block with the previous ciphertext block.

CBC requires an Initialization Vector, commonly called an IV.

The IV should be unpredictable and must be handled correctly.

CBC provides confidentiality but does not automatically provide authentication.

For modern applications, authenticated encryption modes are generally preferable.

CTR Mode

Counter mode converts a block cipher into a stream like construction.

It can be efficient and does not require padding in the same way as CBC.

However, nonce reuse with the same key can seriously compromise security.

GCM Mode

Galois Counter Mode, or GCM, provides authenticated encryption.

This means it can provide both

• Confidentiality

• Integrity and authentication

GCM produces an authentication tag along with the ciphertext.

If the ciphertext or associated data is modified, verification can fail.

For many modern applications, AES GCM is a strong and practical choice.

AES Encryption and Authentication

Encryption alone does not necessarily prove that the ciphertext has not been modified.

For example, an attacker might alter encrypted data while the receiver has no reliable way to determine whether the data was changed.

Authenticated encryption addresses this problem.

AES GCM combines encryption with authentication.

A simplified representation is

Plaintext + Key + Nonce
          ↓
       AES GCM
          ↓
Ciphertext + Authentication Tag
Enter fullscreen mode Exit fullscreen mode

During decryption, the tag is verified.

If verification fails, the application should reject the modified or invalid ciphertext.

Python Libraries for AES

Python does not require developers to manually implement AES mathematical operations.

A commonly used third party library is PyCryptodome.

It provides implementations of AES and several other cryptographic algorithms.

For an academic project, using a well maintained cryptographic library is generally preferable to writing AES from scratch.

Manual implementation is useful for educational study of cryptographic mathematics, but production applications should rely on reviewed cryptographic implementations.

Installing PyCryptodome

The package can be installed using pip.

pip install pycryptodome
Enter fullscreen mode Exit fullscreen mode

After installation, AES can be imported from the Crypto package.

from Crypto.Cipher import AES
Enter fullscreen mode Exit fullscreen mode

Simple AES GCM Example

The following example demonstrates authenticated AES encryption using Python.

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

key = get_random_bytes(32)

message = b"Hello, this is a secret message."

cipher = AES.new(key, AES.MODE_GCM)

ciphertext, tag = cipher.encrypt_and_digest(message)

print("Nonce:", cipher.nonce.hex())
print("Ciphertext:", ciphertext.hex())
print("Authentication Tag:", tag.hex())
Enter fullscreen mode Exit fullscreen mode

In this example, a 32 byte key is generated.

Since

32 bytes × 8 = 256 bits
Enter fullscreen mode Exit fullscreen mode

the program is using AES 256.

The GCM mode also creates a nonce and authentication tag.

AES Decryption in Python

The encrypted information can be decrypted by using the same key and the values generated during encryption.

from Crypto.Cipher import AES

cipher = AES.new(key, AES.MODE_GCM, nonce=cipher.nonce)

plaintext = cipher.decrypt_and_verify(ciphertext, tag)

print("Decrypted message:", plaintext.decode())
Enter fullscreen mode Exit fullscreen mode

The decrypt_and_verify method both decrypts the ciphertext and verifies the authentication tag.

If the ciphertext or tag has been modified, verification should fail.

Complete AES Encryption and Decryption Program

For an assignment, it is useful to create reusable functions.

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes


def encrypt_message(message, key):
    cipher = AES.new(key, AES.MODE_GCM)

    ciphertext, tag = cipher.encrypt_and_digest(
        message.encode()
    )

    return cipher.nonce, ciphertext, tag


def decrypt_message(nonce, ciphertext, tag, key):
    cipher = AES.new(
        key,
        AES.MODE_GCM,
        nonce=nonce
    )

    plaintext = cipher.decrypt_and_verify(
        ciphertext,
        tag
    )

    return plaintext.decode()


key = get_random_bytes(32)

message = "AES encryption in Python"

nonce, ciphertext, tag = encrypt_message(
    message,
    key
)

print("Encrypted data:", ciphertext.hex())

decrypted = decrypt_message(
    nonce,
    ciphertext,
    tag,
    key
)

print("Decrypted data:", decrypted)
Enter fullscreen mode Exit fullscreen mode

Expected Result

The exact ciphertext will be different each time because a fresh nonce is generated.

The output will conceptually look like

Encrypted data: 8f...random hexadecimal data...
Decrypted data: AES encryption in Python
Enter fullscreen mode Exit fullscreen mode

The important result is that the decrypted message matches the original plaintext.

Understanding the Program

The program contains two major functions.

Encryption Function

The encrypt_message function receives the plaintext and key.

def encrypt_message(message, key):
Enter fullscreen mode Exit fullscreen mode

It creates a new AES GCM cipher.

cipher = AES.new(key, AES.MODE_GCM)
Enter fullscreen mode Exit fullscreen mode

The message is then encrypted.

ciphertext, tag = cipher.encrypt_and_digest(
    message.encode()
)
Enter fullscreen mode Exit fullscreen mode

The function returns the nonce, ciphertext, and authentication tag.

Decryption Function

The decryption function receives the nonce, ciphertext, tag, and key.

def decrypt_message(nonce, ciphertext, tag, key):
Enter fullscreen mode Exit fullscreen mode

The same key and nonce are used to initialize the cipher.

cipher = AES.new(
    key,
    AES.MODE_GCM,
    nonce=nonce
)
Enter fullscreen mode Exit fullscreen mode

The ciphertext is then decrypted and verified.

plaintext = cipher.decrypt_and_verify(
    ciphertext,
    tag
)
Enter fullscreen mode Exit fullscreen mode

If authentication succeeds, the original plaintext is returned.

Why Nonces Are Important

A nonce is a value used during encryption to ensure that encryption operations do not unnecessarily repeat the same cryptographic state.

In AES GCM, nonce reuse with the same key is a serious security problem.

Therefore, applications must ensure that a nonce is not reused with the same key.

For an assignment, the simplest approach is to allow the cryptographic library to generate a fresh nonce for every encryption operation.

The nonce does not normally need to be secret. It must, however, be stored or transmitted along with the ciphertext so that decryption can reconstruct the required state.

Why the Authentication Tag Matters

The authentication tag allows the receiver to verify that the encrypted message has not been modified.

Suppose the ciphertext is changed before decryption.

A secure GCM implementation should detect the modification during verification.

Therefore, the application should not simply decrypt data without checking authentication.

A good rule is

Decrypt only after successful authentication
Enter fullscreen mode Exit fullscreen mode

Encrypting a File

AES can also be used to protect files.

A simple academic project can read a file, encrypt its contents, and write the encrypted output to another file.

For example, the project could have

input.txt
    ↓
AES GCM Encryption
    ↓
encrypted.bin
Enter fullscreen mode Exit fullscreen mode

The decryption process reverses this operation.

encrypted.bin
    ↓
AES GCM Decryption
    ↓
output.txt
Enter fullscreen mode Exit fullscreen mode

When implementing file encryption, the key must be handled separately from the encrypted file.

Passwords and AES Keys

A common beginner mistake is to directly use a human password as an AES key.

Passwords are usually not suitable as cryptographic keys because people tend to choose passwords that have much less entropy than randomly generated cryptographic keys.

If a password must be used to derive an encryption key, a password based key derivation function should be used.

Examples include

• PBKDF2

• scrypt

• Argon2

These functions are designed to make password guessing more difficult.

A secure design should also use a unique salt.

AES Key Management

Strong encryption is not useful if the key is poorly protected.

Important key management principles include

• Do not hard code secret keys in production source code

• Do not publish keys in Git repositories

• Do not place keys directly inside public configuration files

• Use secure key storage where appropriate

• Restrict access to encryption keys

• Rotate keys when required by the application's security design

For a classroom assignment, a randomly generated key can be demonstrated. In a production system, key management should receive much more attention.

Testing AES Encryption

A good AES project should include several tests.

Test 1: Normal Message

Encrypt a normal message and decrypt it.

Expected result is that the decrypted message matches the original.

Test 2: Empty Message

Test an empty plaintext if supported by the chosen implementation.

Test 3: Long Message

Use a larger message to verify that the implementation handles more data.

Test 4: Modified Ciphertext

Change one or more ciphertext bytes and verify that authentication fails.

Test 5: Incorrect Key

Attempt decryption with a different key and confirm that verification fails.

Test 6: Different Encryption Runs

Encrypt the same plaintext multiple times using fresh nonces.

The resulting ciphertext should normally differ.

Sample Test Table

Test Input Expected Result
Normal message Short text Correct decryption
Long message Large text Correct decryption
Modified ciphertext Changed encrypted data Authentication failure
Wrong key Different key Authentication failure
Fresh nonce Same plaintext Different ciphertext
Empty input Empty data Implementation dependent

Testing demonstrates that the encryption system is functioning correctly and also helps identify implementation mistakes.

Common AES Implementation Mistakes

Using ECB Mode

ECB can reveal patterns in structured data.

Authenticated encryption modes such as GCM are generally more appropriate for modern application designs.

Reusing a GCM Nonce

Nonce reuse with the same key can seriously compromise security.

Every encryption operation should use an appropriate fresh nonce.

Using a Weak Key

Keys should be generated using a secure random mechanism or derived through a suitable password based key derivation process.

Hard Coding Keys

Putting secret keys directly into source code is unsafe for real applications.

Ignoring Authentication

Encryption without integrity protection can leave applications vulnerable to undetected modification.

Using a Password Directly

Human readable passwords should not normally be used directly as AES keys.

Writing AES From Scratch

Implementing cryptographic primitives manually is error prone. For practical applications, established cryptographic libraries should be preferred.

Exposing Secret Data in Logs

Applications should avoid printing secret keys or sensitive plaintext unnecessarily.

AES Security Considerations

AES itself is only one part of a secure encryption system.

A secure application also needs to consider

• Key generation

• Key storage

• Nonce management

• Authentication

• Randomness

• Password protection

• Access control

• Secure error handling

• Secure data storage

Using a strong encryption algorithm does not automatically make the complete application secure.

AES Project Architecture

A small academic AES encryption project can use the following structure.

aes-project/
│
├── main.py
├── encryption.py
├── decryption.py
├── test_crypto.py
├── requirements.txt
├── README.md
│
└── data/
    ├── input.txt
    └── encrypted.bin
Enter fullscreen mode Exit fullscreen mode

The encryption module can contain encryption functions.

The decryption module can contain decryption functions.

The testing module can verify the implementation.

The data directory can contain test files.

Possible GUI Project

Students can make the assignment more interesting by adding a graphical interface.

A simple GUI can provide

--------------------------------
        AES Encryption
--------------------------------

Enter Message

[________________________]

[ Encrypt ]

Encrypted Data

[________________________]

[ Decrypt ]

Decrypted Message

[________________________]
Enter fullscreen mode Exit fullscreen mode

Python libraries such as Tkinter can be used to create a basic interface.

The interface can allow the user to enter a message, generate or load a key, encrypt the message, and decrypt it.

For a classroom project, this provides a practical demonstration of how cryptography can be integrated into an application.

AES Compared With Asymmetric Encryption

AES is a symmetric encryption algorithm.

Asymmetric cryptography uses a public key and private key.

Feature AES Asymmetric Cryptography
Key model Shared secret key Public and private keys
Performance Generally fast Generally slower
Large data encryption Suitable Usually less suitable
Key distribution Requires secure key sharing Public key can be shared
Examples AES RSA, ECC

Modern security systems often use both symmetric and asymmetric cryptography.

For example, asymmetric techniques can help establish or exchange keying material, while symmetric encryption can protect the actual data efficiently.

AES Applications

AES is used in many areas of computing and cybersecurity.

File Encryption

Sensitive documents can be encrypted before storage.

Database Protection

Sensitive information can be encrypted at the application or storage layer.

Secure Communication

AES can be part of secure communication protocols.

Backup Protection

Encrypted backups can reduce the impact of unauthorized access.

Cloud Storage

Encryption can protect stored data in cloud environments.

Mobile Applications

Applications may use encryption to protect sensitive local data.

Advantages of AES

Strong Security

AES is a widely studied and established cryptographic standard.

Efficient

AES can process data efficiently.

Flexible Key Sizes

Applications can choose between multiple standard key lengths.

Broad Support

Many programming languages and cryptographic libraries support AES.

Suitable for Large Data

As a symmetric cipher, AES is efficient for encrypting substantial amounts of information.

Limitations of AES

Key Management

The security of AES depends heavily on protecting the key.

Incorrect Mode Selection

Using an inappropriate mode can weaken the overall security design.

Implementation Errors

Incorrect nonce handling or authentication verification can introduce serious vulnerabilities.

Does Not Solve Authentication Alone

Basic encryption does not automatically establish who sent the message.

Password Problems

Poor password handling can undermine an otherwise strong encryption algorithm.

How to Improve the Assignment

Students can extend the basic project with additional functionality.

Possible improvements include

• File encryption

• File decryption

• AES 128, 192, and 256 comparison

• Password based key derivation

• Graphical user interface

• Encryption performance measurement

• Authentication failure testing

• Secure key storage demonstration

• Multiple file support

• Encryption history

• Unit testing

A more advanced project can compare AES GCM with another authenticated encryption approach and explain the differences.

Suggested Assignment Report Structure

A complete academic report can use the following structure.

Chapter 1

Introduction to encryption and data security.

Chapter 2

AES background and symmetric cryptography.

Chapter 3

AES key sizes and encryption modes.

Chapter 4

System requirements and project objectives.

Chapter 5

Python implementation.

Chapter 6

Encryption and decryption workflow.

Chapter 7

Testing and results.

Chapter 8

Security considerations.

Chapter 9

Advantages and limitations.

Chapter 10

Future scope.

Chapter 11

Conclusion.

References

Include the official documentation and academic resources used for the project.

Future Scope

AES based projects can be expanded into more advanced cybersecurity applications.

Future implementations can include secure file storage systems, encrypted cloud backups, secure messaging applications, password based encryption, key management systems, database encryption, and secure document sharing.

Students can also explore how AES is integrated with asymmetric cryptography in real world secure communication systems.

Another useful direction is studying authenticated encryption and comparing different secure modes based on performance, usability, and security properties.

Role of Assignment Dude

Students working on cryptography assignments may find it difficult to combine mathematical concepts with practical programming.

Assignment Dude can help students understand the structure of an AES project, explain encryption and decryption concepts, organize Python code, prepare testing scenarios, and structure the final academic report.

However, students should understand how their implementation works rather than simply copying code. A strong assignment should explain the purpose of the key, nonce, authentication tag, encryption mode, and decryption process.

Conclusion

Implementing AES Encryption in Python is an effective way to understand both cryptography and practical programming.

AES is a symmetric block cipher that supports 128 bit, 192 bit, and 256 bit keys. It is widely used because it provides strong security and efficient data processing when implemented correctly.

A Python library such as PyCryptodome makes it possible to use AES without manually implementing the underlying cryptographic mathematics. For modern application designs, authenticated encryption modes such as AES GCM are particularly useful because they provide confidentiality along with integrity and authentication.

A successful AES assignment should demonstrate more than simply converting plaintext into ciphertext. It should explain how keys are generated and managed, why nonces are important, how authentication tags protect data integrity, how encryption and decryption work, and how the implementation can be tested.

The project can also be extended into file encryption, GUI applications, password based encryption, secure storage, and other cybersecurity applications.

By completing an AES encryption project in Python, students gain practical knowledge of symmetric cryptography, secure programming, key management, authenticated encryption, and cybersecurity principles.

Frequently Asked Questions

What is AES encryption?

AES is a symmetric block encryption standard used to protect digital information using a secret cryptographic key.

What key sizes does AES support?

AES supports 128 bit, 192 bit, and 256 bit keys.

What is AES GCM?

AES GCM is an authenticated encryption mode that provides both confidentiality and integrity protection.

Why is GCM useful?

GCM provides an authentication tag that allows the receiver to detect unauthorized modification of encrypted data.

Is AES symmetric encryption?

Yes. AES is a symmetric encryption algorithm because the same secret key is used for encryption and decryption.

Can AES encrypt files?

Yes. AES can be used to encrypt files as well as individual messages.

Should AES keys be stored in source code?

No. Hard coding secret keys is inappropriate for production applications because anyone with access to the source code could potentially obtain the key.

Can a password be used directly as an AES key?

A human password should generally not be used directly as an AES key. A suitable password based key derivation function should be used when passwords are part of the design.

Why is a nonce required in AES GCM?

A nonce helps ensure that encryption operations do not reuse the same cryptographic state. Reusing a GCM nonce with the same key can seriously compromise security.

What happens if ciphertext is modified?

With authenticated encryption such as AES GCM, modification should cause authentication verification to fail.

Which Python library can be used for AES?

PyCryptodome is a commonly used Python cryptographic library that provides AES implementations.

Should students implement AES from scratch?

For learning the underlying mathematics, implementing individual concepts can be educational. For practical applications, established cryptographic libraries are generally preferable because cryptographic implementations are difficult to develop correctly.

What is the difference between AES 128 and AES 256?

Both use a 128 bit block size, but AES 128 uses a 128 bit key while AES 256 uses a 256 bit key and more encryption rounds.

What should an AES assignment include?

A complete assignment should include AES theory, symmetric encryption, key sizes, encryption modes, Python implementation, encryption and decryption workflow, testing, security considerations, common mistakes, applications, limitations, future scope, and conclusion.

Top comments (0)