When you are sending your request from android, encrypt your payload using some encryption, probably RSA, and then decrypt that request on your server side, if decrypted successfully, you can be sure that the request is genuine and is not altered.
Generate a private key file in PHP
$config = array(
"digest_alg" => "sha512",
"private_key_bits" => 4096,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
$keys = openssl_pkey_new($config);
$priv = openssl_pkey_get_private($keys);
openssl_pkey_export_to_file($priv, 'private.pem');
Generate a public .der-file from the private key file with OpenSSL
openssl rsa -in private.pem -pubout -outform DER -out public.der
Import and use the public key in Java (Android side):
File pubKeyFile = new File("public.der");
DataInputStream dis = new DataInputStream(new FileInputStream(pubKeyFile));
byte[] keyBytes = new byte[(int) pubKeyFile.length()];
dis.readFully(keyBytes);
dis.close();
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKey publicKey = (RSAPublicKey)keyFactory.generatePublic(keySpec);
Encode your payload in Android (get bytes according to your requirement)
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
String payload = "tejashwi kalp taru";
byte[] encryptedBytes = Base64.getEncoder().encode(cipher.doFinal(payload.getBytes()));
String encryptedData = new String(encryptedBytes));
//send encryptedData to server for decryption
Decrypt your payload in PHP:
$fp = fopen("private.pem", "r");
$privateKey = fread($fp, 8192);
fclose($fp);
$res = openssl_get_privatekey($privateKey);
$cipher = base64_decode($cipher);
openssl_private_decrypt( $cipher, $decrypted, $res, OPENSSL_PKCS1_OAEP_PADDING );
// $decrypted is the result
Git repo for demo: https://github.com/tejashwikalptaru/encrypted-communication