1

I have a client (android device) that generates a public+private key pair. It sends the public key to a server and the server should encrypt some data using the public key and return it so the client can decrypt it using the private key later. My php code logs a warning stating that the public key I am providing it is invalid.

On the device side, I generate the key pair as follows -

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(256); KeyPair kp = kpg.generateKeyPair(); PublicKey publicKey = kp.getPublic(); 

I then base64 encode and POST it -

String urlParameters = "productID=" + productID + "&publicKey=" + URLEncoder.encode(Base64.encodeToString(publicKey.getEncoded(), Base64.DEFAULT)); // without the URLEncoder, the + signs // are turned into spaces 

On the server side, I extract the publicKey from the POST parameters and try to use it for encoding some data -

$publicKey = $_POST['publicKey']; $encryptedData = ''; $productData = 'test test test'; openssl_public_encrypt($productData, $encryptedData, $publicKey); 

This ends up erroring out with the following in the log -

PHP Warning: openssl_public_encrypt(): key parameter is not a valid public key 

I have also tried adding prefix and suffix to the public key before using it for encryption but that did not help either -

$publicKey = "-----BEGIN PUBLIC KEY-----\r\n" . $publicKey . "\r\n-----END PUBLIC KEY-----"; 

Have broken my head over this for a while and none of the suggestions I came across online seem to help. Any thoughts would be most helpful!

3
  • sighs... how does PHP get away with such poor documentation? The manual page doesn't even say what format the public key should be in! Commented Feb 23, 2013 at 15:27
  • Note that sending a public key to another party is not enough to avoid man in the middle attacks; how do you know that the public key is from the right party? Anybody may send you a public key... Commented Feb 23, 2013 at 17:08
  • @owlstead: you have a good point there. i was sending a public key to the server so i could avoid hardcoding/bundling private key on the device side by generating them on the fly. if i instead use a symmetric key and not pass it around, i am concerned that the key may be extracted from the android package. need to think over this some more i guess.. Commented Feb 24, 2013 at 5:14

1 Answer 1

1

Managed to solve the issue finally by making 2 changes -

  1. Had to use the Base64.NO_WRAP flag instead of Base64.DEFAULT on the Java side.
  2. Added the prefix/suffix in php after chunk splitting - $publicKey = "-----BEGIN PUBLIC KEY-----\r\n" . chunk_split($publicKey) . "-----END PUBLIC KEY-----";
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.