[英]Python library for RSA public decryption
我正在尋找一個能夠使用RSA_PKCS1_PADDING
解密和加密 RSA( RSA_PKCS1_PADDING
是RSA_PKCS1_PADDING
)的 python 庫。 我已經嘗試過pycryptodome
、 cryptography
和rsa
,但它們都無法使用公鑰解密。 我搜索了數百個帖子,所有答案都沒有用,所以要過濾它們:
理想情況下,它應該類似於 nodejs 的crypto.publicDecrypt()
和crypto.publicEncrypt()
。 即使不是庫,也請幫我找到一個能夠做到這一點的函數。 我瀏覽了數百個帖子,我覺得我快瘋了。 謝謝你。
正如您所說,確實可以使用私有加密和使用公共解密,RSA 中的數學對稱性允許只交換密鑰中的 e/d,然后調用加密/解密函數。
話雖如此,我想強調的是,我不是加密專家,不能肯定地說這不會損害安全性。
因此,您可以使用該交換邏輯擴展 RSA-Key 類,使用 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
一直返回sentinel
而不是解密數據。 我決定查看庫源代碼,並檢查如果我在.../Crypto/Cipher/PKCS1_v_1_5.py
注釋掉這些行, .decrypt()
返回什么:
if not em.startswith(b'\x00\x02') or sep < 10:
return sentinel
令我驚訝的是它返回了解密的消息! 不確定我沒有破壞某些東西,但它有效。 我想這是一個錯誤? 這已經在他們的 github repo 中修復了,但該版本尚未發布
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.