【问题标题】:Do not understand the error I am receiving?不明白我收到的错误?
【发布时间】:2019-07-26 10:07:54
【问题描述】:

我有一个我已经大大简化的函数,它计算用于解密仿射密码的乘法和加法密钥,它在某些情况下有效,但在这种情况下它会抛出一个错误,我不确定为什么。这是我的代码:

def InverseMod(a, m):
    for i in range(1,m):
        if ( m*i + 1) % a == 0:
            return ( m*i + 1) // a
    return 'These are not co-prime.'

def decryption_keys_affine(p1, p2, C1, C2, AL):

    s = InverseMod(p1 - p2, AL) * (C1 - C2)

    r = (InverseMod(s, AL) * C2 - p2) % AL

    print("INV(S):", InverseMod(s, AL), "\n" + "R:", r)

当我给它这个输入时,它会输出正确的答案,即 17 和 26:

>>> decryption_keys_affine(3, 20, 19, 20, 42)
INV(S): 17 
R: 26

当我给它这个输入时,它会抛出这个错误:

>>> decryption_keys_affine(5, 20, 9, 26, 26)
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    decryption_keys_affine(5, 20, 9, 26, 26)
  File "C:\Users\Herman\Desktop\crypto_math_functions.py", line 96, in decryption_keys_affine
    r = (InverseMod(s, AL) * C2 - p2) % AL
TypeError: unsupported operand type(s) for -: 'str' and 'int'

它应该输出:

>>> decryption_keys_affine(5, 20, 9, 26, 26)
INV(S): 7 
R: 20

【问题讨论】:

  • Traceback 说这条线 -r = (InverseMod(s, AL) * C2 - p2) % AL - 导致了错误。我想p2 那时已经变成了str(InverseMod(s, AL) * C2 的结果是一个 int - 反之亦然。在该语句之前打印内容以查看它们是什么或Catch the error 并检查/打印除套件中的相关数据。也许考虑学习pdb 模块。
  • @the4horsemen 产生错误的第二个输入试图计算strint 之间的减法:r = ('These are not co-prime.' - p2) % AL

标签: python python-3.x cryptography cryptanalysis


【解决方案1】:

InverseMod() 中,如果这些计算不是素数,则您设置了一个条件,返回“A string”。所以该函数返回一个字符串,r 语句就变成了

r = ("String" * int - int) % int

不正确

要么返回 0 要么做一些if 条件来解决它

【讨论】:

    【解决方案2】:

    这个函数InverseMod针对不同的情况返回不同的类型。如果循环中没有通过if 测试或者循环没有执行,则返回一个字符串。

    def InverseMod(a, m):
        for i in range(1,m):
            if ( m*i + 1) % a == 0:
                return ( m*i + 1) // a
        return 'These are not co-prime.'
    

    一般来说,这种行为应该用异常来建模。

    如果有,故障模式会更加明显。

    def InverseMod(a, m):
        for i in range(1,m):
            if ( m*i + 1) % a == 0:
                return ( m*i + 1) // a
        raise  ValueError('"{}" and "{}" are not co-prime'.format(a, m))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-04
      • 1970-01-01
      • 2016-02-03
      • 1970-01-01
      • 1970-01-01
      • 2018-04-20
      • 2011-07-04
      • 2016-05-20
      相关资源
      最近更新 更多