Code: Select all
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from Crypto import Random
from Crypto.Math.Numbers import Integer
from Crypto.Cipher import PKCS1_OAEP
def decryptRsa(rsaEncryptedData):
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))
variant1 = 0 # tried 0/1
if variant1:
f=open("res\key.pem")
priv = f.read()
f.close()
rky=RSA.import_key(priv)
cipher = PKCS1_v1_5.new(rky)
sentinel = Random.new().read(len(rsaEncryptedData))
rky.__class__ = SwappedRsaKey
decryptData = cipher.decrypt(rsaEncryptedData, sentinel)
if decryptData == sentinel:
print("rsa decrypt failed!")
return
else:
fh =open("res\key.pem","rb")
privkey = serialization.load_pem_private_key(fh.read() , password=None)
fh.close()
decryptData = privkey.decrypt(rsaEncryptedData,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label = None
)
)
return decryptedData