python - 如何使用 PyCrypto 导出的 RSA 公钥解密消息?

标签 python rsa pycrypto

我遇到了这个挑战,我要求使用导出的公钥解密加密的消息。我得到了 3 个文件:

  1. 加密Python脚本
  2. 加密消息
  3. 导出的公钥

我尝试导入公钥然后解密,但我想我必须找出私钥才能解密消息。

加密代码为:

import gmpy
from Crypto.Util.number import *
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5

message = open('message', 'r').read() * 30

def ext_rsa_encrypt(p, q, e, msg):
    m = bytes_to_long(msg)
    while True:
        n = p * q
        try:
            phi = (p - 1)*(q - 1)
            d = gmpy.invert(e, phi)
            pubkey = RSA.construct((long(n), long(e)))
            key = PKCS1_v1_5.new(pubkey)
            enc = key.encrypt(msg).encode('base64')
            return enc
        except:
            p = gmpy.next_prime(p**2 + q**2)
            q = gmpy.next_prime(2*p*q)
            e = gmpy.next_prime(e**2)

p = getPrime(128)
q = getPrime(128)
n = p*q
e = getPrime(64)
pubkey = RSA.construct((long(n), long(e)))
f = open('pubkey.pem', 'w')
f.write(pubkey.exportKey())
g = open('msg.enc', 'w')
g.write(ext_rsa_encrypt(p, q, e, message))

最佳答案

正如评论中所指出的,256 个键非常小,可以轻松分解。首先,您必须重建 key 生成中使用的素数。使用 openssl 查找模数和指数是一件简单的事情:

$ openssl rsa -in <your-public-key> -pubin -text -modulus

这应该输出类似的内容

Exponent: <decimal-value> (<hex-value>)
Modulus=<hex-value>

现在您可以使用 msieve 对模进行因式分解或在 https://factordb.com/ 中搜索它数据库。这将为您提供“p”和“q”。 由于加密代码不完全是 RSA,因此您必须编写自己的解密函数,该函数应如下所示:

def ext_rsa_decrypt(p, q, e, msg):
    m = bytes_to_long(msg)
    while True:
        n = p * q
        try:
            phi = (p - 1)*(q - 1)
            d = gmpy.invert(e, phi)
            privkey = RSA.construct((long(n), long(e), long(d)))
            key = PKCS1_v1_5.new(privkey)
            enc = key.decrypt(msg, "a")
            return enc
        except Exception, ex:
            traceback.print_exc()
            p = gmpy.next_prime(p**2 + q**2)
            q = gmpy.next_prime(2*p*q)
            e = gmpy.next_prime(e**2)

现在您应该拥有解密消息所需的一切,只是不要忘记在将加密消息传递给解密函数之前对其进行 Base64 解码。

关于python - 如何使用 PyCrypto 导出的 RSA 公钥解密消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39434243/

相关文章:

python - 高效的通用Python内存

python - Django - 在模型中,created_at 是一个 UNIX 时间戳

c++ - 什么库或软件盲目签名和验证?

php - RSA加密: Create a cipher text in PHP and decrypt it in Javascript

python - python中的pycrypto和crypto包有什么区别?

javascript - 使 CryptoJS 和 pycrypto 兼容

mysql - 使用 mysql AES 从 Django 加密和解密

python - matplotlib boxplot 绘制 < > 大于和小于某个值

python - Windows 中的 Pygame : ImportError: DLL load failed

c - 从模数和指数加载 rsa key ,加密字符串,然后进行核心转储