I have implemented an python Django system which uses RSA public key encryption.When user makes an api request they need to encrypt the data using the public key and it is decrypted using private key in the python server side.
I was able to implement the system using angular where data encrypted in the angular side is successfully decrypted in the python server side.
Now we need to implement the same using php. But here I am facing an issue, because the data encrypted using the php was unable to decypted in the server side.
Error during decryption
ValueError: Decryption Failed.
This is python code for encryption and decryption.
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
....
public_key = ... #get the public key
msg_in_bytes = str.encode(message) #string to byte conversion
try:
encrypted = public_key.encrypt(msg_in_bytes,padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),algorithm=hashes.SHA256(),label=None))
except Exception as e:
logger.error(e)
......
private_key = .. #get the private key
msg_in_bytes = b64decode(message) #Decode Base64 encoded string
# print(msg_in_bytes)
try:
decrypted = private_key.decrypt(msg_in_bytes,padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),algorithm=hashes.SHA256(),label=None))
And here is the PHP code
json_data=...
openssl_public_encrypt($json_data, $encrypted, $public_key,OPENSSL_PKCS1_OAEP_PADDING);
I am fairly new in PHP coding. Please help if there is any error in php implementations.I assume that there is some issues in padding since python side has options to specify for the padding method while PHP side not.
I will not be able to change the python side code since it is working with angluar and other implementation too
OPENSSL_PKCS1_OAEP_PADDINGusesMGF1-SHA1instead ofMGF1-SHA256and there is no way to set this inopenssl_public_encryptand in python you're usingMGF1-SHA256. You'll need to changeMGF1-SHA256toMGF1-SHA1in python. Ref: stackoverflow.com/q/35779799/2324206 php.net/manual/en/function.openssl-public-encrypt.php#118466