【问题标题】:how to decrypt a message using exported RSA public key with PyCrypto?如何使用导出的 RSA 公钥和 PyCrypto 解密消息?
【发布时间】:2017-01-18 22:37:27
【问题描述】:

我遇到了这个挑战,我要求使用导出的公钥解密加密消息。我得到了 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 位密钥(原文如此!)非常小。您可以使用(一般)数字字段筛实现来分解模数。
  • @ArtjomB。谢谢,我现在创建了私钥,但是如何使用“key = PKCS1_v1_5.new(privatekey); key.decrypt(encmsg.decode('base64'))”解密消息? PKCS1_v1_5 需要一个哨兵。我怎样才能知道哨兵才能解密?
  • 哨兵是一个对象,您可以在出现解密错误时取回。你决定哨兵是什么。 -1 可能是哨兵。 "chicken" 可能是哨兵。你明白了。
  • @ArtjomB.,再次感谢! key.decrypt(encmsg.decode('base64'),"---") 返回错误“密文长度不正确”。我使用 n、e、d(以及与原始公钥完全对应的私钥)以正确的方式构建了密钥。有什么办法可以解决这个问题?
  • @RAHAB2 您可能必须使用密钥大小来拆分消息。

标签: python rsa pycrypto


【解决方案1】:

正如 cmets 中指出的,256 键非常小,可以轻松分解。首先,您必须重建密钥生成中使用的素数。使用 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 解码。

【讨论】:

    猜你喜欢
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    • 2021-10-03
    • 1970-01-01
    相关资源
    最近更新 更多