简体   繁体   English

如何使用python查找数字的素因

[英]How to find the prime factors of a number with python

I'm writing a program that will calulate the private key for a weak RSA public key. 我正在编写一个程序,它将为较弱的RSA公钥计算私钥。 I am wondering how I would go about determining the values for p and q from the value n . 我想知道如何从值n确定pq的值。 Here is the Python code so far: 到目前为止,这是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

The .math module referenced above: .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)

What I need to do appears to be referenced here but this code is in Java. 我需要执行的操作似乎在这里被引用但是此代码是Java语言。

If anyone knows how to get p and q from n with python, help would be appreciated. 如果有人知道如何使用python从n获取pq ,将不胜感激。

Many thanks, Legorooj. 非常感谢,Legolooj。

Mandatory warning: if you are after performance, you will need to investigate the details of the algorithms yourself. 强制警告:如果您追求性能,则需要亲自调查算法的详细信息。 Even "weak" public keys will take forever to crack with a simplistic algorithm (eg Erathostene's sieve). 即使是“弱”的公钥,也将通过简单的算法(例如Erathostene的筛子)永远破解。

That being said, sympy.ntheory.factorint() might be what you need: 话虽这么说, sympy.ntheory.factorint()可能就是您需要的:

from sympy.ntheory import factorint

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

After lots of googling, and pdf reading, I found an algorithm that works. 经过大量的Google搜索和pdf阅读后,我发现了一种有效的算法。 Here is a python implementation: 这是一个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

This algorithm effectively finds the P/Q factors of a small RSA key. 该算法有效地找到了一个小的RSA密钥的P / Q因子。 (I have tested it against a 64-bit PEM public key) (我已经针对64位PEM公钥对其进行了测试)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM