如何在代码中解决RSA问题? (蟒蛇)

时间:2018-11-29 18:55:42

标签: python rsa

我有一个问题,其中RSA实现在特定的代码行中不起作用:

def chooseKeys():
    """
    Selects two random prime numbers from a list of prime numbers which has
    values that go up to 100k. It creates a text file and stores the two
    numbers there where they can be used later. Using the prime numbers,
    it also computes and stores the public and private keys in two separate
    files.
    """

    # choose two random numbers within the range of lines where
    # the prime numbers are not too small and not too big
    rand1 = random.randint(100, 300)


    rand2 = random.randint(100, 300)

    # store the txt file of prime numbers in a python list
    fo = open('primes-to-100k.txt', 'r')
    lines = fo.read().splitlines()
    fo.close()

    # store our prime numbers in these variables
    prime1 = int(lines[rand1])
    prime2 = int(lines[rand2])

    # compute n, totient, e
    n = prime1 * prime2
    totient = (prime1 - 1) * (prime2 - 1)
    e = chooseE(totient)

    # compute d, 1 < d < totient such that ed = 1 (mod totient)
    # e and d are inverses (mod totient)
    gcd, x, y = xgcd(e, totient)

    # make sure d is positive
    if (x < 0):
        d = x + totient
    else:
        d = x

    # write the public keys n and e to a file
    f_public = open('public_keys.txt', 'w')
    f_public.write(str(n) + '\n')
    f_public.write(str(e) + '\n')
    f_public.close()

    f_private = open('private_keys.txt', 'w')
    f_private.write(str(n) + '\n')
    f_private.write(str(d) + '\n')
    f_private.close()

这里的问题是这一行:

   # store the txt file of prime numbers in a python list
fo = open('primes-to-100k.txt', 'r')
lines = fo.read().splitlines()
fo.close()

它总是说 发生了异常:FileNotFoundError

[Errno 2] No such file or directory: 'primes-to-100k.txt'

为此,我尝试使用该文件的路径,但没有用,尝试使用相对路径,这也没有用,针对此问题的任何解决方案

1 个答案:

答案 0 :(得分:0)

我看不到文件primes-to-100k.txt写入磁盘的位置,只能读入它,也无法验证文件是否与发布的代码一起存在于目录中。异常确实意味着它无法在指定的路径中找到该文件,该文件不存在或路径错误。

我担心应用程序的整体安全性,内置的随机模块可以根据数学公式运行,而某些python密码库(如PyCryptodome的Random模块则使用系统进程状态等进行随机化)可以工作。问题在于数学公式倾向于重复数字,而并非真正是随机的。您将得到重复的数据。向您敞开心bru。

以下是该库中的一些示例,可用于安全地执行您想要的操作:

https://pycryptodome.readthedocs.io/en/latest/src/examples.html

指向有关随机模块随机性的更多信息的链接:

Is random.sample truly random?