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!