Android应用内计费签名验证在php服务器


Android in-app billing signature verification in php server

我正在我的android应用程序中的IAB v3工作。每次成功购买后,我希望我的应用程序将签名数据和签名发送回我的php服务器,以便通过google开发者控制台生成的公钥进行验证。我找到了以下代码:

<?php
// $data and $signature are assumed to contain the data and the signature
// fetch public key from certificate and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pubkeyid = openssl_get_publickey($cert);
// state whether signature is okay or not
$ok = openssl_verify($data, $signature, $pubkeyid);
if ($ok == 1) {
    echo "good";
} elseif ($ok == 0) {
    echo "bad";
} else {
    echo "ugly, error checking signature";
}
// free the key from memory
openssl_free_key($pubkeyid);
?>

现在我有一个问题。google给出的公钥是String Base64 Encoded。我不知道如何将该字符串键转换为"。pem"格式。

如果我把我的Base64编码密钥"$pubkeyid"在上面的代码。将给出警告。

Warning: openssl_verify() [function.openssl-verify]: supplied key param cannot be coerced into a public key in myxxx.php.

如何将字符串Base64编码的公钥转换为php接受格式?

有人有上述经验或解决方案吗?请帮助。多谢。

要将从Google获得的base64编码的长公钥转换为可以在PHP中使用的公钥,请执行以下操作:

$base64EncodedPublicKeyFromGoogle = "..."; // This is the public key for your app you get from Google.
$openSslFriendlyKey = "-----BEGIN PUBLIC KEY-----'n" . chunk_split($base64EncodedPublicKeyFromGoogle, 64, "'n") .  "-----END PUBLIC KEY-----";

然后你可以把它传递给openssl_get_publickey()

$publicKeyId = openssl_get_publickey($openSslFriendlyKey);
如你所见,Google的格式几乎是正确的。它只需要被分成64个字符的行,并在右侧的页眉/页脚前加上/追加。

您也可以使用OpenSSL命令像这样转换公钥:

openssl enc -base64 -d -in publickey.base64 -A | openssl rsa -inform DER -pubin > publickey.pem

然后用PHP读取生成的publickey.pem文件,并将其内容传递给openssl_get_publickey()函数

这个API解决了我的问题。

https://github.com/mgoldsborough/google-play-in-app-billing-verification

海报问题的完整解决方案:

<?php
// $data and $signature are assumed to contain the data and the signature
// Paste your google public key below:
$base64EncodedPublicKeyFromGoogle  = "###############################"
//Convert the key to the right format for open SSL
$openSslFriendlyKey = "-----BEGIN PUBLIC KEY-----'n" . chunk_split($base64EncodedPublicKeyFromGoogle, 64, "'n") .  "-----END PUBLIC KEY-----";
$publicKeyId = openssl_get_publickey($openSslFriendlyKey);
// free the key from memory
openssl_free_key($publicKeyId);
//Perform signature verification. Don't forget to decode the signature!
$ok = openssl_verify($data, base64_decode($signature), $publicKeyId, OPENSSL_ALGO_SHA1);
if ($ok == 1) {
    echo "good";
} elseif ($ok == 0) {
    echo "bad";
} else {
    echo openssl_error_string();
}
?>