猿问

我的仿射密码密码分析无法 100% 正常工作

我必须创建一个函数,将输入作为来自英语语言“p1”和“p2”的频率分析以及密文“C1”和“C2”的频率分析的字母作为字母长度,我使用“AL”。我在 Python 中创建了一个函数来执行此操作,但它仅在某些时候有效。其他时候它给我一个错误,我不知道为什么。这两个方程是: s(r+p1)=C1(mod AL) s(r+p2)=C2(mod AL)


该代码应该计算用于解密给定密文的乘法和加法密钥。


这是我的代码 - 第一个函数计算乘法模逆,第二个函数实现方程。


def ModInverse(a, m):

    if gcd(a, m) != 1:

        return 'These are not co-prime.'


    # Calculate using the Extended Euclidean Algorithm:

    u1, u2, u3 = 1, 0, a

    v1, v2, v3 = 0, 1, m

    while v3 != 0:

        q = u3 // v3

        v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3

    return u1 % m

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


    s = p2 - p1


    p3 = s * p1


    p4 = (p3 % AL)


    p5 = C1 - p4


    p6 = AL + p5


    p7 = ModInverse(s, AL)


    p8 = p7 * p6


    r = p8 % AL


    multi = ModInverse(s, AL)

    add = AL - r


    print(multi, add)

当我给它这个输入时:


>>> decryption_keys_affine(5, 20, 9, 26, 26)

7 20

>>> 

它显示正确的答案。


当我给它这个输入时:


>>> decryption_keys_affine(5, 20, 41, 18, 42)

Traceback (most recent call last):

  File "<pyshell#0>", line 1, in <module>

    decryption_keys_affine(5, 20, 41, 18, 42)

  File "C:\Users\Herman\Desktop\crypto_math_functions.py", line 108, in decryption_keys_affine

    r = p8 % AL

TypeError: not all arguments converted during string formatting

它给了我那个错误,我不知道为什么。(第一个字母长度为 26,第二个字母长度包括 10 个数字和 6 个符号,使其为 42)。


紫衣仙女
浏览 162回答 1
1回答

萧十郎

原因是这一行:return 'These are not co-prime.'在%操作者进行的模运算时施加到整数。当应用于strings 时,它会执行字符串格式化。在提供给的参数ModInverse不是互质的情况下,它返回一个r = p8 % AL尝试格式化的字符串。由于返回字符串不包含格式说明符,因此会引发异常。在这种情况下,不要返回字符串,而应该引发自己的异常,例如:def ModInverse(a, m):&nbsp; &nbsp; if gcd(a, m) != 1:&nbsp; &nbsp; &nbsp; &nbsp; raise ValueError('The input arguments, {} and {}, are not coprime.'.format(a, m))&nbsp; &nbsp; # Calculate using the Extended Euclidean Algorithm:&nbsp; &nbsp; u1, u2, u3 = 1, 0, a&nbsp; &nbsp; v1, v2, v3 = 0, 1, m&nbsp; &nbsp; while v3 != 0:&nbsp; &nbsp; &nbsp; &nbsp; q = u3 // v3&nbsp; &nbsp; &nbsp; &nbsp; v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3&nbsp; &nbsp; return u1 % m
随时随地看视频慕课网APP

相关分类

Python
我要回答