【问题标题】:How to find the prime factors of a number with python如何用python找到一个数的质因数
【发布时间】:2019-10-21 19:34:29
【问题描述】:

我正在编写一个程序来计算弱 RSA 公钥的私钥。我想知道如何从值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)

我需要做的似乎被引用了 here 但这段代码是用 Java 编写的。

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

非常感谢,Legorooj。

【问题讨论】:

  • SO 不是免费的代码转换服务。转换为 Python,然后发布带有问题的代码。
  • 我知道。我根本不懂 Java,我希望 SO 能够帮助解决如何使用 python 从n 获取pq
  • 你懂手动操作吗?如果不是,那么你真的有一个数学问题,而不是一个编程问题(尤其不是 Python 问题)。如果你这样做了,那么从那里开始,如果你不能让实现工作,请提出一个更具体的问题。
  • 我认为您不了解分解作为两个近似相等素数乘积的大整数的难度,即 RSA 模数。如果没有大量硬件和/或时间,您将无法做到。
  • 幸运的是我两者都有。 @KarlKnechtel,我了解如何手动操作,并且已经找到了实现它的方法 - 目前仅作为伪代码。如果可行,我将回答我自己的问题。如果没有,我会问一个新问题,为什么实施不起作用。

标签: python encryption rsa primes cryptanalysis


【解决方案1】:

强制警告:如果您追求性能,则需要自己调查算法的细节。使用简单的算法(例如 Erathostene 的筛子),即使是“弱”公钥也需要永远破解。

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

from sympy.ntheory import factorint

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

【讨论】:

  • 感谢您的回答,但 smpy.ntheory.factorint() 使用此测试整数的时间太长:9236378997685682877721661094972497924039685752827371833327322710323377895840902638303442492100881746878186386244383135186587004052271180780932725919664899
  • math.log(your number, 2) 返回 ~512。同样,即使是“弱”的公钥也需要永远破解。 Wikipedia 页面en.wikipedia.org/wiki/… 让我认为 RSA-512 对使用 Python 的随机人来说仍然是一个难以破解的难题,即使使用起来不安全(因为攻击者是可以使用体面硬件的数论家)。
  • 这也引出了您使用程序的目的的问题,因为我敢打赌周围有一些企业仍在使用 RSA-512...
  • 我将使用我的程序来攻击我想出的一个密码配方——一个与 pgp 相似的密码配方
【解决方案2】:

经过大量谷歌搜索和 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 公钥对其进行了测试)

【讨论】:

    猜你喜欢
    • 2019-06-12
    • 2013-04-11
    • 1970-01-01
    • 2016-03-17
    • 2017-02-15
    • 2023-01-13
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    相关资源
    最近更新 更多