如何用 python 求一个数的质因数

How to find the prime factors of a number with python

我正在编写一个程序来计算弱 RSA public 密钥的私钥。我想知道如何根据值 n 确定 pq 的值。到目前为止,这是 Python 代码:

from Crypto.PublicKey import RSA #PyCryptoDome
import .math as cm # My own module

with open(public_keyfile, 'rb') as key: # Public Keyfile Is in PEM format
    public_key = RSA.import_key(key)

n = public_key.n # N value of the public_key

e = public_key.e # E value of the public_key

p, q = get_factors_of(n) # This I don't know how to do, though there is a question that might help [see bottom]

t = cm.lcm(p-1, q-1) # Get the lowest common multiple of q and q

d = cm.mod_inverse(e, t) # Get d, the modular inverse of e % t

private_key = RSA.construct((n, e, d, p, q) # Construct the RSA private_key

上面引用的 .math 模块:

from math import gcd


def mod_inverse(a, b):
    a = a % b
    for x in range(1, b):
        if (a * x) % b == 1:
            return x
    return 1


def lcm(x, y):
    return x * y // gcd(x, y)

我需要做的似乎被引用了 但此代码在 Java.

如果有人知道如何使用 python 从 n 获得 pq,将不胜感激。

非常感谢,Legorooj。

强制警告:如果你追求的是性能,你需要自己研究算法的细节。即使 "weak" public 密钥也需要永远用简单的算法(例如 Erathostene 的筛法)破解。

话虽如此,sympy.ntheory.factorint() 可能正是您所需要的:

from sympy.ntheory import factorint

print(factorint(54))  # {2: 1, 3: 3} i.e. 54 == 2**1 * 3**3

经过大量谷歌搜索和 pdf 阅读后,我找到了一种有效的算法。这是一个 python 实现:

import math
def get_factors_of(num):
    poss_p = math.floor(math.sqrt(num)) 

    if poss_p % 2 == 0: # Only checks odd numbers, it reduces time by orders of magnitude
        poss_p += 1
    while poss_p < num:
        if num % poss_p == 0:
            return poss_p
        poss_p += 2

该算法有效地找到了小型 RSA 密钥的 P/Q 个因素。 (我已经针对 64 位 PEM public 密钥对其进行了测试)