0

0

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

心靈之曲

心靈之曲

发布时间:2025-10-02 18:33:13

|

261人浏览过

|

来源于php中文网

原创

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

本文针对 Python 中使用 Crypto 库进行 AES 加密解密时出现解密后文本为空的问题,提供了一种解决方案。通过分析代码,指出问题在于密钥处理方式,并提供修正后的代码示例,确保加密解密流程的正确性。同时,本文还包含完整的加密解密示例代码,方便读者理解和应用。

在使用 Python 的 Crypto 库进行 AES 加密和解密时,可能会遇到解密后文本为空的情况。这通常是由于密钥处理不当引起的。下面将详细分析并提供解决方案。

问题分析

提供的代码中,AESCipher 类的 get_key 方法使用 base64 编码密钥:

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

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

然而,在构造 AESCipher 对象时,如果提供了密钥,代码会计算密钥的 SHA256 摘要:

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 = hashlib.sha256(key.encode()).digest()
        else:
            self.key = Random.new().read(self.block_size)

这意味着,当从文件中读取密钥并用于解密时,实际上使用的是密钥的 SHA256 摘要,而不是原始密钥。由于加密时使用的密钥与解密时使用的密钥不一致,导致解密结果为空。

解决方案

ECTouch移动商城系统
ECTouch移动商城系统

ECTouch是上海商创网络科技有限公司推出的一套基于 PHP 和 MySQL 数据库构建的开源且易于使用的移动商城网店系统!应用于各种服务器平台的高效、快速和易于管理的网店解决方案,采用稳定的MVC框架开发,完美对接ecshop系统与模板堂众多模板,为中小企业提供最佳的移动电商解决方案。ECTouch程序源代码完全无加密。安装时只需将已集成的文件夹放进指定位置,通过浏览器访问一键安装,无需对已有

下载

正确的做法是,当提供密钥时,应该对密钥进行 base64 解码,而不是计算摘要。修改后的构造函数如下:

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)

完整代码示例

下面是包含修复后的代码的完整示例,并添加了一些改进,使其更易于使用和理解:

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


class AESCipher(object):
    def __init__(self, key=None):
        # 初始化 AESCipher 对象,如果提供了密钥,则使用提供的密钥,否则生成随机密钥
        self.block_size = AES.block_size
        if key:
            try:
                self.key = b64decode(key.encode())
            except Exception as e:
                raise ValueError("Invalid key format. Key must be a base64 encoded string.") from e
        else:
            self.key = Random.new().read(self.block_size)

    def encrypt(self, plain_text):
        # 使用 AES 在 CBC 模式下加密提供的明文
        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)
        # 将 IV 和加密文本组合,然后进行 base64 编码以进行安全表示
        return b64encode(iv + encrypted_text).decode("utf-8")

    def decrypt(self, encrypted_text):
        # 使用 AES 在 CBC 模式下解密提供的密文
        try:
            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).decode('utf-8')
        except Exception as e:
            raise ValueError("Decryption failed.  Check key and ciphertext.") from e

    def get_key(self):
        # 获取密钥的 base64 编码表示
        return b64encode(self.key).decode("utf-8")

    def __pad(self, plain_text):
        # 向明文添加 PKCS7 填充
        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):
        # 从明文中删除 PKCS7 填充
        last_byte = plain_text[-1]
        if not isinstance(last_byte, int):
            raise ValueError("Invalid padding")
        return plain_text[:-last_byte]


def save_to_notepad(text, key, filename):
    # 将加密文本和密钥保存到文件
    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():
    # 获取用户输入,加密并保存到文件
    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()

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


def decrypt_from_file():
    # 使用密钥从文件解密加密文本
    filename = input("Enter the filename to decrypt (including .txt extension): ")
    try:
        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_text = aes_cipher.decrypt(encrypted_text)

        print("Decrypted Text:", decrypted_text)

    except FileNotFoundError:
        print(f"Error: File '{filename}' not found.")
    except Exception as e:
        print(f"Error during decryption: {e}")


def encrypt_and_decrypt_in_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_text = aes_cipher.decrypt(encrypted_text)
    print("Decrypted Text:", decrypted_text)


# 菜单界面
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.")

注意事项

  • 确保安装了 pycryptodome 库,可以使用 pip install pycryptodome 命令安装。
  • 密钥的安全性至关重要,请妥善保管密钥。
  • 在实际应用中,建议使用更安全的密钥管理方案,例如使用硬件安全模块 (HSM)。
  • 异常处理是必不可少的,在实际应用中,应该添加更完善的异常处理机制。

总结

通过修正密钥处理方式,可以解决 Python AES 加密解密后文本为空的问题。 在实际应用中,需要注意密钥的安全性,并采取适当的密钥管理措施。 同时,完善的异常处理机制也是保证代码健壮性的重要组成部分。

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
pip安装使用方法
pip安装使用方法

安装步骤:1、确保Python已经正确安装在您的计算机上;2、下载“get-pip.py”脚本;3、按下Win + R键,然后输入cmd并按下Enter键来打开命令行窗口;4、在命令行窗口中,使用cd命令切换到“get-pip.py”所在的目录;5、执行安装命令;6、验证安装结果即可。大家可以访问本专题下的文章,了解pip安装使用方法的更多内容。

339

2023.10.09

更新pip版本
更新pip版本

更新pip版本方法有使用pip自身更新、使用操作系统自带的包管理工具、使用python包管理工具、手动安装最新版本。想了解更多相关的内容,请阅读专题下面的文章。

416

2024.12.20

pip设置清华源
pip设置清华源

设置方法:1、打开终端或命令提示符窗口;2、运行“touch ~/.pip/pip.conf”命令创建一个名为pip的配置文件;3、打开pip.conf文件,然后添加“[global];index-url = https://pypi.tuna.tsinghua.edu.cn/simple”内容,这将把pip的镜像源设置为清华大学的镜像源;4、保存并关闭文件即可。

761

2024.12.23

python升级pip
python升级pip

本专题整合了python升级pip相关教程,阅读下面的文章了解更多详细内容。

351

2025.07.23

2026赚钱平台入口大全
2026赚钱平台入口大全

2026年最新赚钱平台入口汇总,涵盖任务众包、内容创作、电商运营、技能变现等多类正规渠道,助你轻松开启副业增收之路。阅读专题下面的文章了解更多详细内容。

32

2026.01.31

高干文在线阅读网站大全
高干文在线阅读网站大全

汇集热门1v1高干文免费阅读资源,涵盖都市言情、京味大院、军旅高干等经典题材,情节紧凑、人物鲜明。阅读专题下面的文章了解更多详细内容。

23

2026.01.31

无需付费的漫画app大全
无需付费的漫画app大全

想找真正免费又无套路的漫画App?本合集精选多款永久免费、资源丰富、无广告干扰的优质漫画应用,涵盖国漫、日漫、韩漫及经典老番,满足各类阅读需求。阅读专题下面的文章了解更多详细内容。

28

2026.01.31

漫画免费在线观看地址大全
漫画免费在线观看地址大全

想找免费又资源丰富的漫画网站?本合集精选2025-2026年热门平台,涵盖国漫、日漫、韩漫等多类型作品,支持高清流畅阅读与离线缓存。阅读专题下面的文章了解更多详细内容。

6

2026.01.31

漫画防走失登陆入口大全
漫画防走失登陆入口大全

2026最新漫画防走失登录入口合集,汇总多个稳定可用网址,助你畅享高清无广告漫画阅读体验。阅读专题下面的文章了解更多详细内容。

9

2026.01.31

热门下载

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

精品课程

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

共4课时 | 22.4万人学习

Django 教程
Django 教程

共28课时 | 3.7万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.3万人学习

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

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