Python 用于 RSA public 解密的库

Python library for RSA public decryption

我正在寻找一个 python 库,它能够使用 public 密钥解密和加密 RSA(准确地说是 RSA_PKCS1_PADDING)。我已经尝试过 pycryptodomecryptographyrsa,但它们都无法使用 public 密钥解密。我翻了几百个帖子,所有的答案都没有用,所以过滤一下:

  1. 我没有混淆 public 密钥和私钥
  2. Public解密是可能的(我做到了here
  3. 别无他法。我实际上需要向服务器发送 public 加密消息,并接收私人加密消息并使用 public 密钥
  4. 解密它们

理想情况下应该是nodejs的crypto.publicDecrypt()crypto.publicEncrypt()。请帮我找到即使不是图书馆,也只是一个能够做到这一点的功能。我浏览了数百个帖子,感觉自己快要疯了。谢谢。

正如您所说,确实可以使用 private 加密并使用 public 解密,RSA 中的数学对称性允许仅交换密钥中的 e/d,然后调用 encrypt/decrypt函数。

话虽这么说,但我想强调的是,我不是加密专家,不能肯定地说这不会危及安全。

因此,您可以使用该交换逻辑扩展 RSA 密钥 class,使用 blackmagic 交换加载密钥的实现,并将其传递给普通函数:

from Crypto.PublicKey.RSA import RsaKey
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Math.Numbers import Integer

class SwappedRsaKey(RsaKey):
    def _encrypt(self, plaintext):
        # normally encrypt is p^e%n
        return int(pow(Integer(plaintext), self._d, self._n))
    def _decrypt(self, ciphertext):
        # normally decrypt is c^d%n
        return int(pow(Integer(ciphertext), self._e, self._n))

data = "I met aliens in UFO. Here is the map.".encode("utf-8")

# It's important to also use our swapped logic in encryption step, otherwise the lib would still use e&n (the private contains all 3 values).

private_key = RSA.import_key(open("mykey.pem").read())
private_key.__class__ = SwappedRsaKey
public_key = RSA.import_key(open("mykey.pub").read())
public_key.__class__ = SwappedRsaKey

cipher_priv = PKCS1_OAEP.new(private_key)
cipher_pub = PKCS1_OAEP.new(public_key)

enc_data = cipher_priv.encrypt(data)

# Decrypt again, just a showcase to prove we can get the value back
dec_data = cipher_pub.decrypt(enc_data)

print(dec_data.decode("utf-8"))

首先,非常感谢 Tobias K. 简短而明确的回答。它运行完美。

但是当我尝试解密服务器消息时,pycryptodome 保留 returning sentinel 而不是解密数据。我决定查看库源代码,并检查如果我在 .../Crypto/Cipher/PKCS1_v_1_5.py:

中注释掉这些行, .decrypt() return 会发生什么
if  not em.startswith(b'\x00\x02') or sep < 10:
    return sentinel

令我惊讶的是它return解密了消息!不确定我没有破坏某些东西,但它确实有效。我想这是一个错误?这已经在他们的 github 存储库中得到修复,但该版本尚未发布