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

macOS终端运行Python ECB检测程序无输出问题排查

问题

尝试运行一段Python代码,但在macOS终端中始终没有任何输出。代码需要实现两个方法:countRepetitions(接收密文参数,返回所有16字节块的总重复次数)和detectECBMode(接收密文输入,判断是否存在块重复,返回布尔值标识是否为ECB模式加密)。期望程序读取密文文件后,输出ECB加密的十六进制格式密文及其重复次数。以下是代码:

from Crypto.Cipher import AES
from collections import Counter

def countRepetitions(ciphertext):
    blocks = [ciphertext[i:i+16] for i in range(0, len(ciphertext), 16)]
    return sum(count-1 for count in Counter(blocks).values())

def detectECBMode(ciphertext):
    blocks = [ciphertext[i:i+16] for i in range(0, len(ciphertext), 16)]
    return len(blocks) != len(set(blocks))

# Open the file and read all the lines
with open('ciphertexts.txt', 'r') as f:
    ciphertexts = [line.strip() for line in f]

# Iterate over each ciphertext and check if it was encrypted using ECB mode
for ciphertext in ciphertexts:
    if detectECBMode(ciphertext):
        repetitions = countRepetitions(ciphertext)
        print(f"Ciphertext in ECB mode -{ciphertext}")
        print(f"Repetitions - {repetitions}")
        break  # Stop after finding the first ciphertext encrypted using ECB mode

运行后终端无输出,寻求问题原因及解决方法。

问题原因及解决方法
  • 核心逻辑错误:块分割单位错误
    ECB模式的块是16字节,对应32个十六进制字符。当前代码直接把十六进制字符串按16字符分割,相当于把8字节当成一个块,完全不符合ECB块检测的逻辑,导致无法识别出重复块。
    解决:先将十六进制字符串解码为二进制字节串,再按16字节分割块。修改后,两个方法的参数应为二进制字节串,而非原始十六进制字符串。

  • 文件读取异常

    • 确认ciphertexts.txt与代码在同一目录,或使用绝对路径打开文件;若文件为空,循环无执行逻辑,自然无输出。
    • 检查文件内容:每行必须是完整的合法十六进制字符串,无多余空格或无效字符。
  • 未处理解码异常
    若文件中存在非法十六进制行,程序会直接崩溃但无明确提示。需添加异常捕获,跳过无效行并给出提示。

  • 冗余导入
    代码中导入的AES未被使用,可删除该语句以简化代码。

修改后的完整代码

from collections import Counter

def countRepetitions(cipher_bytes):
    # 按16字节分割二进制密文
    blocks = [cipher_bytes[i:i+16] for i in range(0, len(cipher_bytes), 16)]
    return sum(count-1 for count in Counter(blocks).values())

def detectECBMode(cipher_bytes):
    blocks = [cipher_bytes[i:i+16] for i in range(0, len(cipher_bytes), 16)]
    return len(blocks) != len(set(blocks))

with open('ciphertexts.txt', 'r') as f:
    ciphertexts = [line.strip() for line in f]

for ciphertext in ciphertexts:
    try:
        cipher_bytes = bytes.fromhex(ciphertext)
        if detectECBMode(cipher_bytes):
            repetitions = countRepetitions(cipher_bytes)
            print(f"Ciphertext in ECB mode: {ciphertext}")
            print(f"Repetitions: {repetitions}")
            break
    except ValueError:
        print(f"Invalid hex string: {ciphertext}, skipping...")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 17:53:02