You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现AES解密报错求助:ord()参数类型错误

Fixing AES Decryption Errors

Key Issues in Your Code:

  1. Missing IV Handling: CBC mode requires an Initialization Vector (IV). The encrypted data includes the IV prepended to the ciphertext—your code wasn't extracting it.
  2. Incorrect Block Size: AES uses a fixed 16-byte block size, but your pad/unpad functions used 32 bytes.
  3. Bytes vs String Mismatch: The unpad function tried to use ord() on a byte value (which is already an integer), causing the TypeError.
  4. Forgot to Set Key: Your execution code didn't call set_key() before decrypting.

Corrected Code

import hashlib
from Crypto.Cipher import AES
import base64

class AESFunction:
    secret_key = None
    decrypted_string = None
    encrypted_string = None

    @staticmethod
    def set_key(my_key):
        key = bytes.fromhex(my_key)
        sha = hashlib.sha256()
        sha.update(key)
        key = sha.digest()[:32]
        AESFunction.secret_key = key

    @staticmethod
    def get_decrypted_string():
        return AESFunction.decrypted_string

    @staticmethod
    def set_decrypted_string(decrypted_string):
        AESFunction.decrypted_string = decrypted_string

    @staticmethod
    def get_encrypted_string():
        return AESFunction.encrypted_string

    @staticmethod
    def set_encrypted_string(encrypted_string):
        AESFunction.encrypted_string = encrypted_string

    @staticmethod
    def encrypt(str_to_encrypt):
        cipher = AES.new(AESFunction.secret_key, AES.MODE_CBC)
        encrypted_bytes = cipher.encrypt(AESFunction.pad(str_to_encrypt).encode('utf-8'))
        # Prepend IV to encrypted data (matches PHP's openssl_encrypt behavior)
        AESFunction.set_encrypted_string(base64.b64encode(cipher.iv + encrypted_bytes).decode('utf-8'))

    @staticmethod
    def decrypt(str_to_decrypt):
        decoded_data = base64.b64decode(str_to_decrypt)
        # Extract IV (first 16 bytes) and ciphertext
        iv = decoded_data[:16]
        ciphertext = decoded_data[16:]
        
        cipher = AES.new(AESFunction.secret_key, AES.MODE_CBC, iv)
        decrypted_bytes = cipher.decrypt(ciphertext)
        AESFunction.set_decrypted_string(AESFunction.unpad(decrypted_bytes).decode('utf-8'))

    @staticmethod
    def pad(text):
        block_size = AES.block_size  # 16 bytes for AES
        pad_len = block_size - (len(text) % block_size)
        padding = chr(pad_len) * pad_len
        return text + padding

    @staticmethod
    def unpad(text):
        pad_len = text[-1]  # text is bytes, so last element is an integer
        return text[:-pad_len]

Execution Code

str_password = "f4622a74c54b81f0404c1b6589e8f96c"
str_to_decrypt = "yH0lcZaFBnG3usii6UXZovCYKZYXFUuZF5vcmT+Tz59FQw2pgkke97F/O9BrlEEB3WcqxxdgoVVq+uKxg3y14HzWmByy+f7ck68eyjxULgdCjwka666rDPjm0Tf/+jjnteSbtVPc9WRLuhaPiFBblI9aK3B38ApECDCNvvRjwE+GtfeGqcu1tCo9aTJAwXroN58Tvu6Otn2quNHyLjUrDEfSzsifkGS8rdid6J+c4VZsK87pALA/CIQxtA7z8W91f+x2bb5EfH8nglfBpsE1FP9IBnI5ECjVTJy9pM45TJhnHSYOIRHX5jcwMSUDLgBdjJ57EHdzf0RqTO4ZdLHv7xpMSsVP1oHClqbGTd9UE/yXt9a2Fvm+rPKAL9rU9tXtMCe6uONgnRELrn2VePJYcp3qViP/1HReN4IbT4EYUlXJ/Tqdph6YERTKUh67mnF4lPfHCsrb9AsPNcMYn7r8tT5dMgC1wjzXO22+tUuD8DWEbnrHPPID1WBCRua3POBMyGUcMkSIEdke739pDoKxW1Ww6iGsbsQX60g5jiJEAg6fghn6P+6osKXrfLO4OirsUo8SKRO1m6YSMf31htvkcJbUbDAe2nG+aeUxEozdVyRxUauMtxYahvqcQPJtEKgAugPoCYrPx+RhutoPyaHOOzUtzXvznOV+2qcE0HfLaSotFPeteQzx7Qj4lKDVNkmkwn8jRyVfMUFzRp01v6DqsJe89uIdTyAe65rpyzNt17TDOR8BWLxifOAhDosrW61RfFE+HBU3egySbfs3PxJxHUOrwBOhnGQwILN+bENaLgcQCjczgs9BZ3i+6XK7DwLNFL1xBt42i09NpyIbJYXE1ZkrObA9rrmGLhHCqkhIDyBAaWYYNOdYOVIRbUWSA+bSeCg6xIgy/FhhxxNsmtYAMzrdjQyjYIIEuAvhe9wOTP1IPNqbtuyEPoObThCtZy3JunneK4SdW5f5rzNDOPu4dHw1EuRBYNmqmXh2Mpw2LWoit/+8Eob4aiZDpeH3HJAXrXHH+lyulJgxm4fkHZXcj25ISr0OOHjuLqAIn7ezceeRnLSfHkjL74klt0aRCIuG0p6MKwVVdHEX2n4WblcYHgEHNUoWWpOb9I3gf6Egb5uk59u9Sjc+9/MRaXoIulv+qgRNDGVMByEIqNlpmPSKnwWEEmtV54aa2QjGMOb282tTuEMpha9uHrgBfEwsKeXZ6Uwx1SPyvNHa5eoTojLc7avBdU//5XwPLp40DRvuLo6Kn6fY2SMeWRqP8A4LtarU+2eYwqWkdeggJFF3LFBkYDDwh9N+j8mBdtv1sg/bguD6yUE3UUN/jZ9nhxraxt9qrP11ifXnvSK5BToa7t5SFBiMDCM/n/bBINd+N05937KStvC76AsZHFvxl4xVZq2200qDCYzSrGbVrRcJUABvvlXm1EGHWAQcfe9K5UJ5KZIwijd9p1e2OReHNOziw1VGYR3vZ45ZkqNQnRaqYacnmXEGYgXa7ik92PWarE148+TRdoDBC1jPHRNejXNx9KRoU88cZiGENRjm80jTxZ4tWgVFDzS99GhsHkZw2+4pHZNN06gZce1KsQnnx+algAYK"

# Set the key first
AESFunction.set_key(str_password)
# Decrypt the string
AESFunction.decrypt(str_to_decrypt)
# Get the result
decrypted_string = AESFunction.get_decrypted_string()
print("Decrypted string:", decrypted_string)

Explanation of Fixes:

  • IV Extraction: The first 16 bytes of the decoded encrypted data are used as the IV, which is required for CBC mode decryption.
  • Block Size: Changed to use AES.block_size (16 bytes) instead of hardcoding 32, aligning with AES standards.
  • Unpad Fix: Removed ord() since the input is bytes, where each element is already an integer representing the byte value.
  • Key Setup: Added the missing call to set_key() before decrypting.

This code will correctly decrypt your data to the expected JSON result.

内容的提问来源于stack exchange,提问作者Harshit verma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 20:35:05