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

Hill密码加密函数实现出现TypeError,请求排查解决

Hill密码加密函数错误排查与修复

问题重现

实现的Hill密码加密函数,当输入明文为"ACT"、密钥为"GYBNQKURP"时,预期输出密文"POH",但运行时在代码行ciphertext_vector[i] = (ciphertext_vector[i] + vector[j] * key[i * n + j]) % 26抛出错误:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

错误原因

  1. 密钥类型未转换:传入的密钥是字符串(如"GYBNQKURP"),代码直接使用字符串中的字符参与数值运算,字符与整数无法进行乘法/加法操作,导致类型错误。
  2. 字符转换逻辑错误:最后将数值转回字符时,使用chr(num % 65),这会生成ASCII值为0-25的不可见字符,正确逻辑应该是将0-25的数值加65,转回A-Z的大写字母。

修复步骤

  • 将密钥字符串转换为数值矩阵:遍历密钥的每个字符,通过ord(c) - 65转换为0-25的整数,与明文的数值化逻辑保持一致。
  • 修正字符转换代码:将chr(num % 65)替换为chr(num + 65),确保数值正确映射回大写字母。

修正后的完整代码

def encrypt(plaintext, key):
    # Calculate the size of the key matrix
    n = int(len(key) ** 0.5)
    # Convert key string to numeric matrix (0-25)
    key_matrix = [ord(c) - 65 for c in key]
    # If the message length is not a multiple of n, pad it with 'X'
    if len(plaintext) % n != 0:
        plaintext += 'X' * (n - len(plaintext) % n)
    # Split the message into n-character blocks and convert each block to a vector of numbers
    blocks = [plaintext[i:i + n] for i in range(0, len(plaintext), n)]
    block_vectors = [[ord(char) - 65 for char in block] for block in blocks]
    # Multiply each block vector by the key matrix and take the result mod 26
    ciphertext_vectors = []
    for vector in block_vectors:
        ciphertext_vector = [0] * n
        for i in range(n):
            for j in range(n):
                ciphertext_vector[i] = (ciphertext_vector[i] + vector[j] * key_matrix[i * n + j]) % 26
        ciphertext_vectors.append(ciphertext_vector)
    # Convert each ciphertext vector to a block of characters
    ciphertext_blocks = [''.join([chr(num + 65) for num in vector]) for vector in ciphertext_vectors]
    # Join the ciphertext blocks into a single string and return it
    ciphertext = ''.join(ciphertext_blocks)
    return ciphertext

验证结果

运行encrypt("ACT", "GYBNQKURP"),输出结果为"POH",与预期一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 05:47:30