簡體   English   中英

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

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

我正在編寫一個程序,它將為較弱的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)

我需要執行的操作似乎在這里被引用但是此代碼是Java語言。

如果有人知道如何使用python從n獲取pq ,將不勝感激。

非常感謝,Legolooj。

強制警告:如果您追求性能,則需要親自調查算法的詳細信息。 即使是“弱”的公鑰,也將通過簡單的算法(例如Erathostene的篩子)永遠破解。

話雖這么說, sympy.ntheory.factorint()可能就是您需要的:

from sympy.ntheory import factorint

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

經過大量的Google搜索和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公鑰對其進行了測試)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM