0

0

Python AES 加密解密后文本为空问题的解决方案

心靈之曲

心靈之曲

发布时间:2025-10-02 18:25:01

|

524人浏览过

|

来源于php中文网

原创

python aes 加密解密后文本为空问题的解决方案

本文旨在解决在使用 Python 的 Crypto 库进行 AES 加密解密时,解密后得到空字符串的问题。通过分析代码,找出问题根源在于密钥处理方式不正确,并提供修正后的代码示例,确保加密和解密过程的正确性,最终实现数据的可靠保护。

在使用 Python 的 Crypto 库进行 AES 加密和解密时,有时可能会遇到解密后文本为空的情况。这通常是由于密钥处理不当造成的。以下将详细介绍如何避免这个问题,并提供正确的代码示例。

问题在于,原始代码中,当提供密钥给 AESCipher 构造函数时,错误地计算了密钥的哈希值,而正确的做法应该是对密钥进行 Base64 解码。AESCipher.get_key 方法将密钥编码为 Base64 字符串,因此在解密时需要进行逆向操作。

正确的 AESCipher 构造函数应如下所示:

立即学习Python免费学习笔记(深入)”;

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

关键的修改在于 __init__ 方法中,当 key 参数存在时,使用 b64decode(key.encode()) 对其进行 Base64 解码,而不是计算哈希值。

Kuwebs企业网站管理系统3.1.5 UTF8
Kuwebs企业网站管理系统3.1.5 UTF8

酷纬企业网站管理系统Kuwebs是酷纬信息开发的为企业网站提供解决方案而开发的营销型网站系统。在线留言模块、常见问题模块、友情链接模块。前台采用DIV+CSS,遵循SEO标准。 1.支持中文、英文两种版本,后台可以在不同的环境下编辑中英文。 3.程序和界面分离,提供通用的PHP标准语法字段供前台调用,可以为不同的页面设置不同的风格。 5.支持google地图生成、自定义标题、自定义关键词、自定义描

下载

完整代码示例:

以下是包含修正后的 AESCipher 类的完整代码示例,并包含加密、解密以及保存到文件等功能。

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)


# Menu Interface
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.")

注意事项:

  • 密钥安全: 请务必安全地存储和传输密钥。避免将密钥硬编码到代码中。
  • 编码问题: 在处理文本时,确保使用一致的编码方式(如 UTF-8)。
  • Padding: PKCS7 padding 是 AES 加密常用的填充方式,确保加密和解密都使用相同的填充方式。
  • IV (Initialization Vector): 每次加密都应该使用不同的 IV,以增强安全性。

总结:

通过修正 AESCipher 类的构造函数,确保在解密时正确处理密钥,可以有效解决 AES 解密后文本为空的问题。同时,注意密钥安全、编码一致性以及正确的填充方式,可以提高加密系统的安全性。

相关专题

更多
python开发工具
python开发工具

php中文网为大家提供各种python开发工具,好的开发工具,可帮助开发者攻克编程学习中的基础障碍,理解每一行源代码在程序执行时在计算机中的过程。php中文网还为大家带来python相关课程以及相关文章等内容,供大家免费下载使用。

755

2023.06.15

python打包成可执行文件
python打包成可执行文件

本专题为大家带来python打包成可执行文件相关的文章,大家可以免费的下载体验。

636

2023.07.20

python能做什么
python能做什么

python能做的有:可用于开发基于控制台的应用程序、多媒体部分开发、用于开发基于Web的应用程序、使用python处理数据、系统编程等等。本专题为大家提供python相关的各种文章、以及下载和课程。

758

2023.07.25

format在python中的用法
format在python中的用法

Python中的format是一种字符串格式化方法,用于将变量或值插入到字符串中的占位符位置。通过format方法,我们可以动态地构建字符串,使其包含不同值。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

618

2023.07.31

python教程
python教程

Python已成为一门网红语言,即使是在非编程开发者当中,也掀起了一股学习的热潮。本专题为大家带来python教程的相关文章,大家可以免费体验学习。

1262

2023.08.03

python环境变量的配置
python环境变量的配置

Python是一种流行的编程语言,被广泛用于软件开发、数据分析和科学计算等领域。在安装Python之后,我们需要配置环境变量,以便在任何位置都能够访问Python的可执行文件。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

547

2023.08.04

python eval
python eval

eval函数是Python中一个非常强大的函数,它可以将字符串作为Python代码进行执行,实现动态编程的效果。然而,由于其潜在的安全风险和性能问题,需要谨慎使用。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

577

2023.08.04

scratch和python区别
scratch和python区别

scratch和python的区别:1、scratch是一种专为初学者设计的图形化编程语言,python是一种文本编程语言;2、scratch使用的是基于积木的编程语法,python采用更加传统的文本编程语法等等。本专题为大家提供scratch和python相关的文章、下载、课程内容,供大家免费下载体验。

707

2023.08.11

Golang gRPC 服务开发与Protobuf实战
Golang gRPC 服务开发与Protobuf实战

本专题系统讲解 Golang 在 gRPC 服务开发中的完整实践,涵盖 Protobuf 定义与代码生成、gRPC 服务端与客户端实现、流式 RPC(Unary/Server/Client/Bidirectional)、错误处理、拦截器、中间件以及与 HTTP/REST 的对接方案。通过实际案例,帮助学习者掌握 使用 Go 构建高性能、强类型、可扩展的 RPC 服务体系,适用于微服务与内部系统通信场景。

8

2026.01.15

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 0.8万人学习

Django 教程
Django 教程

共28课时 | 3.1万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.1万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号