Manuj Mittal
Manuj Mittal

Reputation: 107

Passing Encryption/Decryption Keys from Python to PHP?

I am using Python Pycrypto Module to generate RSA key pair:

#!/home/user/Desktop/generate_keys.py

from Crypto.PublicKey import RSA
from Crypto import Random

random_generator = Random.new().read
key = RSA.generate(1024,random_generator)
public_key = key.publickey().exportKey()               #export public key
private_key = key.exportKey()                          #export private key

print(public_key)
print(private_key)

What I need to do is run the script in Python and passing both of the keys to PHP which stores it in database. I am trying to do pass the variable through executing the python script in shell then taking the output in PHP.

<?php

   $command = escapeshellcmd('python3 generate_keys.py');
   $public_key = shell_exec($command);
   echo $public_key;

?>

The problem here is I do not understand how to pass variables from Python to PHP, All I am doing is taking the output of one python script into PHP.

If I try to do it in two separate scripts of Python:

for Public Key:

from Crypto.PublicKey import RSA
from Crypto import Random

random_generator = Random.new().read
key = RSA.generate(1024,random_generator)

print(key.publickey().exportKey())

for Private Key:

from Crypto.PublicKey import RSA
from Crypto import Random

random_generator = Random.new().read
key = RSA.generate(1024,random_generator)

print(key.exportKey())

I will get a different key pair each time I run those random_generator.

How Can I pass variables of Python ('public_key' & 'private_key') to PHP variables?

I have checked some answers about passing variables from python to php and vice-versa but I did not understand. If the communication between php, python and shell can be optimised please inform me. Thank You!

Upvotes: 0

Views: 534

Answers (1)

Headhunter Xamd
Headhunter Xamd

Reputation: 606

You were almost there ;) you can always combine the 2 keys into one string with a delimiter inbetween.

#!/home/user/Desktop/generate_keys.py

from Crypto.PublicKey import RSA
from Crypto import Random

random_generator = Random.new().read
key = RSA.generate(1024,random_generator)
public_key = key.publickey().exportKey()               #export public key
private_key = key.exportKey()                          #export private key

data = public_key + "||" + private_key
print(data)

so when you receive the data in php you can just use explode(delimiter, string) .

<?php

   $command = escapeshellcmd('python3 generate_keys.py');
   $keys = shell_exec($command);
   $splitted_keys = explode("||", $keys);
   echo $splitted_keys[0];

?>

Upvotes: 1

Related Questions