我有这个函数,我已经大大简化了它计算用于解密仿射密码的乘法和加法密钥,它在某些情况下有效,但在这种情况下,它给我一个错误,我不确定为什么。这是我的代码:
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