Reputation: 649
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!
Upvotes: 1
Views: 1215
Reputation: 649
Managed to solve the issue finally by making 2 changes -
Base64.NO_WRAP
flag instead of Base64.DEFAULT
on the Java side.$publicKey = "-----BEGIN PUBLIC KEY-----\r\n" . chunk_split($publicKey) . "-----END PUBLIC KEY-----";
Upvotes: 1