search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
Problem analysis
solution
Complete code example
Things to note
Summarize
Home Backend Development Python Tutorial Solving the problem of empty string after Python AES encryption and decryption

Solving the problem of empty string after Python AES encryption and decryption

Dec 03, 2025 am 06:18 AM

Solving the problem of empty string after Python AES encryption and decryption

This article aims to solve the problem of getting an empty string after decryption when using Python's Crypto library for AES encryption and decryption. By analyzing common causes and providing repaired code examples, we help developers correctly implement AES encryption and decryption functions to ensure safe data transmission and storage.

AES (Advanced Encryption Standard) is a widely used symmetric encryption algorithm that plays an important role in the field of data security. However, when using Python's Crypto library to implement AES encryption and decryption, developers may encounter the problem of obtaining an empty string after decryption. This is usually caused by improper handling of keys. The following details how to properly handle keys, with a complete code example.

Problem analysis

In the provided code, in the __init__ method of the AESCipher class, when the user provides the key, the key is hashed:

 self.key = hashlib.sha256(key.encode()).digest()

The get_key method returns the Base64 encoding of the key:

 return b64encode(self.key).decode("utf-8")

This means that when the key is read from the file and used for decryption, the Base64 encoding of the hashed key is actually used, not the original key. This causes decryption to fail, resulting in an empty string.

solution

The correct approach is that in the AESCipher's constructor, if the key is provided, it should be Base64 decoded rather than hashed. The modified __init__ method is as follows:

 class AESCipher(object):
    def __init__(self, key=None):
        # Initialize the AESCipher object with a key,
        # defaulting to a randomly generated key
        self.block_size = AES.block_size
        if key:
            self.key = b64decode(key.encode())
        else:
            self.key = Random.new().read(self.block_size)

Complete code example

Here is the complete modified code example:

 import hashlib
from Crypto.Cipher import AES
from Crypto import Random
from base64 import b64encode, b64decode


class AESCipher(object):
    def __init__(self, key=None):
        # Initialize the AESCipher object with a key,
        # defaulting to a randomly generated key
        self.block_size = AES.block_size
        if key:
            self.key = b64decode(key.encode())
        else:
            self.key = Random.new().read(self.block_size)

    def encrypt(self, plain_text):
        # Encrypt the provided plaintext using AES in CBC mode
        plain_text = self.__pad(plain_text)
        iv = Random.new().read(self.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        encrypted_text = cipher.encrypt(plain_text)
        # Combine IV and encrypted text, then base64 encode for safe representation
        return b64encode(iv encrypted_text).decode("utf-8")

    def decrypt(self, encrypted_text):
        # Decrypt the provided ciphertext using AES in CBC mode
        encrypted_text = b64decode(encrypted_text)
        iv = encrypted_text[:self.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        plain_text = cipher.decrypt(encrypted_text[self.block_size:])
        return self.__unpad(plain_text)

    def get_key(self):
        # Get the base64 encoded representation of the key
        return b64encode(self.key).decode("utf-8")

    def __pad(self, plain_text):
        # Add PKCS7 padding to the plaintext
        number_of_bytes_to_pad = self.block_size - len(plain_text) % self.block_size
        padding_bytes = bytes([number_of_bytes_to_pad] * number_of_bytes_to_pad)
        padded_plain_text = plain_text.encode() padding_bytes
        return padded_plain_text

    @staticmethod
    def __unpad(plain_text):
        # Remove PKCS7 padding from the plaintext
        last_byte = plain_text[-1]
        return plain_text[:-last_byte] if isinstance(last_byte, int) else plain_text


def save_to_notepad(text, key, filename):
    # Save encrypted text and key to a file
    with open(filename, 'w') as file:
        file.write(f"Key: {key}\nEncrypted text: {text}")
    print(f"Text and key saved to {filename}")

def encrypt_and_save():
    # Take user input, encrypt, and save to a file
    user_input = ""
    while not user_input:
        user_input = input("Enter the plaintext: ")

    aes_cipher = AESCipher() # Randomly generated key

    encrypted_text = aes_cipher.encrypt(user_input)
    key = aes_cipher.get_key()

    filename = input("Enter the filename (including .txt extension): ")
    save_to_notepad(encrypted_text, key, filename)


def decrypt_from_file():
    # Decrypt encrypted text from a file using a key
    filename = input("Enter the filename to decrypt (including .txt extension): ")
    with open(filename, 'r') as file:
        lines = file.readlines()
        key = lines[0].split(":")[1].strip()
        encrypted_text = lines[1].split(":")[1].strip()

    aes_cipher = AESCipher(key)
    decrypted_bytes = aes_cipher.decrypt(encrypted_text)

    # Decoding only if the decrypted bytes are not empty
    decrypted_text = decrypted_bytes.decode("utf-8") if decrypted_bytes else ""
    print("Decrypted Text:", decrypted_text)


def encrypt_and_decrypt_in_command_line():
    # Encrypt and then decrypt user input in the command line
    user_input = ""
    while not user_input:
        user_input = input("Enter the plaintext: ")

    aes_cipher = AESCipher()

    encrypted_text = aes_cipher.encrypt(user_input)
    key = aes_cipher.get_key()

    print("Key:", key)
    print("Encrypted Text:", encrypted_text)

    decrypted_bytes = aes_cipher.decrypt(encrypted_text)
    decrypted_text = decrypted_bytes.decode("utf-8") if decrypted_bytes else ""
    print("Decrypted Text:", decrypted_text)


#MenuInterface
while True:
    print("\nMenu:")
    print("1. Encrypt and save to file")
    print("2. Decrypt from file")
    print("3. Encrypt and decrypt in command line")
    print("4. Exit")

    choice = input("Enter your choice (1, 2, 3, or 4): ")

    if choice == '1':
        encrypt_and_save()
    elif choice == '2':
        decrypt_from_file()
    elif choice == '3':
        encrypt_and_decrypt_in_command_line()
    elif choice == '4':
        print("Exiting the program. Goodbye!")
        break
    else:
        print("Invalid choice. Please enter 1, 2, 3, or 4.")

Things to note

  • Key management: The security of your keys is critical. Don't hardcode keys into your code, instead use a secure way to store and manage keys.
  • Encoding: Make sure to use a consistent encoding, such as UTF-8, during encryption and decryption.
  • Padding: AES requires padding of the plaintext to ensure that its length is a multiple of the block size. PKCS7 is a commonly used padding scheme.
  • IV (Initialization Vector): When using CBC mode, a random IV needs to be used. The IV does not need to be kept secret, but the same IV must be used during encryption and decryption.

Summarize

By handling the key correctly, you can avoid the problem of empty strings after AES decryption. In practical applications, you also need to pay attention to issues such as key management, encoding, and padding to ensure data security. The code examples provided in this article can serve as the basis for AES encryption and decryption, and developers can modify and extend them according to actual needs.

The above is the detailed content of Solving the problem of empty string after Python AES encryption and decryption. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solve the error of multidict build failure when installing Python package Solve the error of multidict build failure when installing Python package Mar 08, 2026 am 02:51 AM

When installing libraries that depend on multidict in Python, such as aiohttp or discord.py, users may encounter the error "ERROR: Could not build wheels for multidict". This is usually due to the lack of the necessary C/C compiler or build tools, preventing pip from successfully compiling multidict's C extension from source. This article will provide a series of solutions, including installing system build tools, managing Python versions, and using virtual environments, to help developers effectively solve this problem.

How to use the Python zip function_Parallel traversal of multiple sequences and dictionary construction How to use the Python zip function_Parallel traversal of multiple sequences and dictionary construction Mar 13, 2026 am 11:54 AM

The essence of zip is zipper pairing, which packs multiple iterable objects into tuples by position and does not automatically unpack the dictionary. When passing in a dictionary, its keys are traversed by default. You need to explicitly use the keys()/values()/items() view to correctly participate in parallel traversal.

How to draw a histogram in Python_Multi-dimensional classification data comparison and stacked histogram color mapping implementation How to draw a histogram in Python_Multi-dimensional classification data comparison and stacked histogram color mapping implementation Mar 13, 2026 pm 12:18 PM

Multi-dimensional classification histograms need to manually calculate the x position and call plt.bar hierarchically; when stacking, bottom must be used to accumulate height, and xticks and ylim must be explicitly set (bottom=0); avoid mixing stacked=True and seaborn, and colors should be dynamically generated and strictly match the layer sequence.

How to find the sum of 5 numbers using Python's for loop How to find the sum of 5 numbers using Python's for loop Mar 10, 2026 pm 12:48 PM

This article explains in detail how to use a for loop to read 5 integers from user input and add them up, provide a concise and readable standard writing method, and compare efficient alternatives to built-in functions.

How Python manages dependencies_Comparison between pip and poetry How Python manages dependencies_Comparison between pip and poetry Mar 12, 2026 pm 04:21 PM

pip is suitable for simple projects, which only install packages and do not isolate the environment; poetry is a modern tool that automatically manages dependencies, virtual environments and version locking. Use pip requirements.txt for small projects, and poetry is recommended for medium and large projects. The two cannot be mixed in the same project.

Python set intersection optimization_large data volume set operation skills Python set intersection optimization_large data volume set operation skills Mar 13, 2026 pm 12:36 PM

The key to optimizing Python set intersection performance is to use the minimum set as the left operand, avoid implicit conversion, block processing and cache incremental updates. Priority should be given to using min(...,key=len) to select the smallest set, disabling multi-parameter intersection(), using frozenset or bloom filters to reduce memory, and using lru_cache to cache results in high-frequency scenarios.

How to store sparse matrices in Python_Dictionary coordinate storage and use of scipy.sparse How to store sparse matrices in Python_Dictionary coordinate storage and use of scipy.sparse Mar 12, 2026 pm 05:48 PM

Use scipy.sparse.coo_matrix instead of a dictionary because the bottom layer uses row/col/data three-array to efficiently support operations; the structure needs to be deduplicated, converted to csr/csc and then calculated; save_npz is preferred for saving; operations such as slicing must use csr/csc format.

How to run a Python script_Detailed explanation of various ways to run a Python script and command line operations How to run a Python script_Detailed explanation of various ways to run a Python script and command line operations Apr 03, 2026 pm 01:51 PM

To run a Python script, make sure that Python is installed, the PATH configuration is correct, and the script has no syntax errors; confirm the interpreter path and version through which/where and --version; shebang only takes effect on Linux/macOS and requires chmod x; when reporting module errors, you need to check the working directory, sys.path, piplist, and running mode.

Related articles