RSA基础解密脚本(使用factordb.com分解n)

Friday, January 6, 2023
本文共434字
1分钟阅读时长

⚠️本文是作者P3troL1er原创,首发于https://peterliuzhi.top/tricks/rsa%E5%9F%BA%E7%A1%80%E8%A7%A3%E5%AF%86%E8%84%9A%E6%9C%AC%E4%BD%BF%E7%94%A8factordb.com%E5%88%86%E8%A7%A3n/。商业转载请联系作者获得授权,非商业转载请注明出处!

Tragedy is a tool for the living to gain wisdom, not a guide by which to live. — Robert F. Kennedy

factordb.com的分解速度很快,解密RSA的过程中我们可能会用到,于是我写了一个基础爬虫python脚本从factordb.com请求数据得到p和q后求逆得到d自动解密c,脚本不是很优雅,如果有师傅能改进,烦请师傅贴在评论区造福后来人,感谢您

脚本

import re
import requests
from bs4 import BeautifulSoup
import gmpy2
from Crypto.Util.number import *

c = 0
n = 0
print(f"[+]n={n}")
p_q = []
# 一般来说需要代理才能连上网络,有些代理加速器也不用这样配置
proxies = {"http": "http://?.?.?.?:?",
           "https": "http://?.?.?.?:?", }
url = "http://factordb.com/index.php?"
html_doc = requests.get(url, params={"query": n}, proxies=proxies)
# 创建一个BeautifulSoup解析对象
soup = BeautifulSoup(html_doc.text, "html.parser", from_encoding="utf-8")
# 获取所有的链接
links = soup.find_all('a')
print("所有的链接:")
full_link = []
for link in links:
    if link is not None \
        and link.get('href') is not None \
            and "index.php?id=" in link.get('href'):
        full_link.append(f"http://factordb.com/{link.get('href')}")
        print(full_link[-1])

# 从链接中获取p和q
for link in full_link:
    html_doc = requests.get(link)
    tmp_soup = BeautifulSoup(
        html_doc.text, "html.parser", from_encoding="utf-8")
    content = tmp_soup.select(
        "body > form > center > input[type=text]:nth-child(1)")
    num = int(content[0].get("value"))
    if num != n:
        p_q.append(num)

p, q = p_q
print(f"[+]p={p}")
print(f"[+]q={q}")
# 求欧拉函数
phi = (p-1)*(q-1)
# 求e的逆d
e = 0
d = gmpy2.invert(e, phi)

# 用私钥解密
m = pow(c, d, n)
print(f"[+]对c={c}的解密结果是:")
result = long_to_bytes(m)
try:
    print(result.decode("UTF-8"))
except Exception as e:
    print(result)

运行结果示例

文内图片