0

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

3
  • 1
    That's because in OPENSSL_PKCS1_OAEP_PADDING uses MGF1-SHA1 instead of MGF1-SHA256 and there is no way to set this in openssl_public_encrypt and in python you're using MGF1-SHA256. You'll need to change MGF1-SHA256 to MGF1-SHA1 in python. Ref: stackoverflow.com/q/35779799/2324206 php.net/manual/en/function.openssl-public-encrypt.php#118466 Commented Jul 2, 2021 at 14:33
  • Thank you for your help, since we have some angular system working alongside with the python we will not be able to change the python side without affecting all of them. So can you suggest any other module in php where I can specify the MGF1-SHA256 which can be used in the place of openssl_public_encrypt Commented Jul 2, 2021 at 14:44
  • phpseclib allows the specification of both digests (both default to SHA256): phpseclib.com/docs/rsa#encryption--decryption Commented Jul 2, 2021 at 15:56

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.