android 开发者网站上的示例应用程序使用 java 代码验证购买 json。有没有人有幸弄清楚如何在 python 中验证购买。特别是在 GAE 中?
以下是android应用内计费的相关摘录example program .这是需要使用 PyCrypto 转换为 python 的内容它被 Google 重写为完全 python,并且是 App Engine 上唯一可用的安全库。希望谷歌对我使用下面的摘录很满意。
private static final String KEY_FACTORY_ALGORITHM = "RSA";
private static final String SIGNATURE_ALGORITHM = "SHA1withRSA";
String base64EncodedPublicKey = "your public key here";
PublicKey key = Security.generatePublicKey(base64EncodedPublicKey);
verified = Security.verify(key, signedData, signature);
public static PublicKey generatePublicKey(String encodedPublicKey) {
try {
byte[] decodedKey = Base64.decode(encodedPublicKey);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
} catch ...
}
}
public static boolean verify(PublicKey publicKey, String signedData, String signature) {
if (Consts.DEBUG) {
Log.i(TAG, "signature: " + signature);
}
Signature sig;
try {
sig = Signature.getInstance(SIGNATURE_ALGORITHM);
sig.initVerify(publicKey);
sig.update(signedData.getBytes());
if (!sig.verify(Base64.decode(signature))) {
Log.e(TAG, "Signature verification failed.");
return false;
}
return true;
} catch ...
}
return false;
}
最佳答案
这是我的做法:
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from base64 import b64decode
def chunks(s, n):
for start in range(0, len(s), n):
yield s[start:start+n]
def pem_format(key):
return '\n'.join([
'-----BEGIN PUBLIC KEY-----',
'\n'.join(chunks(key, 64)),
'-----END PUBLIC KEY-----'
])
def validate_purchase(publicKey, signedData, signature):
key = RSA.importKey(pem_format(publicKey))
verifier = PKCS1_v1_5.new(key)
data = SHA.new(signedData)
sig = b64decode(signature)
return verifier.verify(data, sig)
这假设 publicKey
是您从开发者控制台获取的一行 base64 编码的 Google Play 商店 key 。
对于更愿意使用 m2crypto 的人,validate_purchase()
将更改为:
from M2Crypto import RSA, BIO, EVP
from base64 import b64decode
# pem_format() as above
def validate_purchase(publicKey, signedData, signature):
bio = BIO.MemoryBuffer(pem_format(publicKey))
rsa = RSA.load_pub_key_bio(bio)
key = EVP.PKey()
key.assign_rsa(rsa)
key.verify_init()
key.verify_update(signedData)
return key.verify_final(b64decode(signature)) == 1
关于python - 在 Google App Engine 上用 Python 验证 android 应用内购买消息的签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5440550/