【问题标题】:Verifying signature on android in-app purchase message in Python on Google App Engine在 Google App Engine 上使用 Python 验证 android 应用内购买消息的签名
【发布时间】:2011-03-26 05:38:40
【问题描述】:

android 开发者网站上的示例应用程序使用 java 代码验证购买 json。有没有人幸运地解决了如何在 python 中验证购买。尤其是在 GAE 中?

以下是android应用内计费example program的相关摘录。这是需要使用PyCrypto 转换为python 的内容,该PyCrypto 被Google 重写为完全python,并且是应用程序引擎上唯一可用的安全库。希望谷歌对我使用下面的摘录很酷。

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;
}

【问题讨论】:

  • 我不打算将其发布为答案,因为我无法判断它是否是您正在寻找的确切内容,但试试这个link - Google Code,它展示了如何编写一个 GAE 应用程序,它将用 JSON 响应,我想你可以修改它以提供验证

标签: python android google-app-engine in-app-purchase


【解决方案1】:

我是这样做的:

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 商店密钥。

对于喜欢使用 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

【讨论】:

  • 我必须在validate_purchase(publicKey,signedData,signature) 函数中添加以下行才能使其工作:signedData=signedData.encode("utf8")
  • 谢谢你,你让我开心!您还可以将 Google 许可证转换为有效的公钥,如下所示:openssl enc -base64 -d -in publickey.base64 -A | openssl rsa -inform DER -pubin > publickey.pem
【解决方案2】:

我终于发现您来自 Google Play 的 base64 编码公钥是 X.509 subjectPublicKeyInfo DER SEQUENCE,并且签名方案是 RSASSA-PKCS1-v1_5 而不是 RSASSA-PSS。如果你安装了PyCrypto,其实很简单:

import base64
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5

# Your base64 encoded public key from Google Play.
_PUBLIC_KEY_BASE64 = "YOUR_BASE64_PUBLIC_KEY_HERE"
# Key from Google Play is a X.509 subjectPublicKeyInfo DER SEQUENCE.
_PUBLIC_KEY = RSA.importKey(base64.standard_b64decode(_PUBLIC_KEY_BASE64))

def verify(signed_data, signature_base64):
    """Returns whether the given data was signed with the private key."""

    h = SHA.new()
    h.update(signed_data)
    # Scheme is RSASSA-PKCS1-v1_5.
    verifier = PKCS1_v1_5.new(_PUBLIC_KEY)
    # The signature is base64 encoded.
    signature = base64.standard_b64decode(signature_base64)
    return verifier.verify(h, signature)

【讨论】:

    【解决方案3】:

    现在是 2016 年,下面是使用 cryptography 的方法:

    import base64
    import binascii
    
    from cryptography.exceptions import InvalidSignature
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives import hashes, serialization
    from cryptography.hazmat.primitives.asymmetric import padding
    
    
    class RSAwithSHA1:
        def __init__(self, public_key):
            # the public key google gives you is in DER encoding
            # let cryptography handle it for you
            self.public_key = serialization.load_der_public_key(
                base64.b64decode(public_key), backend=default_backend()
            )
    
        def verify(self, data, signature):
            """
            :param str data: purchase data
            :param str signature: data signature
            :return: True signature verification passes or False otherwise
            """
            # note the signature is base64 encoded
            signature = base64.b64decode(signature.encode())
            # as per https://developer.android.com/google/play/billing/billing_reference.html
            # the signature uses "the RSASSA-PKCS1-v1_5 scheme"
            verifier = self.public_key.verifier(
                signature, padding.PKCS1v15(), hashes.SHA1(),
            )
            verifier.update(data.encode())
            try:
                verifier.verify()
            except InvalidSignature:
                return False
            else:
                return True
    

    【讨论】:

      猜你喜欢
      • 2013-01-14
      • 2012-04-20
      • 2011-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 2014-03-01
      相关资源
      最近更新 更多