Android - protecting in app purchases with server side verification
My small contribution to reduce fraud in in-app purchases
Signature verification on an external server, on your Android code :
verifySignatureOnServer()
private boolean verifySignatureOnServer(String data, String signature) {
String retFromServer = "";
URL url;
HttpsURLConnection urlConnection = null;
try {
String urlStr = "https://www.example.com/verify.php?data=" + URLEncoder.encode(data, "UTF-8") + "&signature=" + URLEncoder.encode(signature, "UTF-8");
url = new URL(urlStr);
urlConnection = (HttpsURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader inRead = new InputStreamReader(in);
retFromServer = convertStreamToString(inRead);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return retFromServer.equals("good");
}
convertStreamToString()
private static String convertStreamToString(java.io.InputStreamReader is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
verify.php on the root directory of web hosting
<?php
// get data param
$data = $_GET['data'];
// get signature param
$signature = $_GET['signature'];
// get key
$key_64 = ".... put here the base64 encoded pub key from google play console , all in one row !! ....";
$key = "-----BEGIN PUBLIC KEY-----\n".
chunk_split($key_64, 64,"\n").
'-----END PUBLIC KEY-----';
//using PHP to create an RSA key
$key = openssl_get_publickey($key);
// state whether signature is okay or not
$ok = openssl_verify($data, base64_decode($signature), $key, OPENSSL_ALGO_SHA1);
if ($ok == 1) {
echo "good";
} elseif ($ok == 0) {
echo "bad";
} else {
die ("fault, error checking signature");
}
// free the key from memory
openssl_free_key($key);
?>
NOTES:
You should encrypt the URL in your java code, if not the URL can be found easy with a simple text search in your decompressed app apk
Also better to change php file name, url arguments, good/bad reponses to something with no sense.
verifySignatureOnServer() should be run in a separated thread if not a network on main thread exception will be thrown. An alternative would be to use Volley.
IN-APP BILLING LIBRARY UPDATE
Using the library, the data to be verified is returned by Purchase.getOriginalJson()
and the signature by Purchase.getSignature()
Hope it will help ...