首页 > 解决方案 > 如何在代码中解决我的 RSA 问题?(Python)

问题描述

我有一个问题,即 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'

所以为此我尝试使用文件的路径,没有用,尝试使用相对路径,也没有用,任何解决方案

标签: pythonrsa

解决方案


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

我担心应用程序的整体安全性,内置的随机模块使用数学公式而不是一些 python 密码库,如 PyCryptodome 的随机模块,它使用系统进程状态等进行随机化。问题是数学公式倾向于重复数字,并不是真正随机的。你最终会得到重复的数据。打开你的蛮力。

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

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

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

random.sample 真的是随机的吗?


推荐阅读