Python AES 加密解密后为空字符串问题的解决

霞舞
发布: 2025-10-02 18:47:26
原创
572人浏览过

python aes 加密解密后为空字符串问题的解决

本文旨在解决在使用 Python 的 Crypto 库进行 AES 加密和解密时,解密后得到空字符串的问题。通过分析常见原因和提供修复后的代码示例,帮助开发者正确实现 AES 加密解密功能,确保数据的安全传输和存储。

AES(Advanced Encryption Standard)是一种广泛使用的对称加密算法,在数据安全领域扮演着重要角色。 然而,在使用 Python 的 Crypto 库实现 AES 加密和解密时,开发者可能会遇到解密后得到空字符串的问题。这通常是由于密钥处理不当造成的。以下将详细介绍如何正确处理密钥,并提供完整的代码示例。

问题分析

在提供的代码中,AESCipher 类的 __init__ 方法中,当用户提供密钥时,会对密钥进行哈希处理:

self.key = hashlib.sha256(key.encode()).digest()
登录后复制

而 get_key 方法返回的是密钥的 Base64 编码

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

AI建筑知识问答
AI建筑知识问答

用人工智能ChatGPT帮你解答所有建筑问题

AI建筑知识问答 22
查看详情 AI建筑知识问答
return b64encode(self.key).decode("utf-8")
登录后复制

这意味着,当从文件中读取密钥并用于解密时,实际上使用的是哈希后的密钥的 Base64 编码,而不是原始密钥。 这会导致解密失败,从而得到空字符串。

解决方案

正确的做法是,在 AESCipher 的构造函数中,如果提供了密钥,则应该对其进行 Base64 解码,而不是进行哈希处理。修改后的 __init__ 方法如下:

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):
        # 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: AES 需要对明文进行填充,以确保其长度是块大小的倍数。 PKCS7 是一种常用的填充方案。
  • IV (Initialization Vector): 在使用 CBC 模式时,需要使用一个随机的 IV。 IV 不需要保密,但必须在加密和解密过程中使用相同的 IV。

总结

通过正确处理密钥,可以避免 AES 解密后得到空字符串的问题。 在实际应用中,还需要注意密钥管理、编码和填充等问题,以确保数据的安全。 本文提供的代码示例可以作为 AES 加密解密的基础,开发者可以根据实际需求进行修改和扩展。

以上就是Python AES 加密解密后为空字符串问题的解决的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

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