Verifying signature on android in-app purchase message in Python on Google App Engine

前端 未结 3 958
借酒劲吻你
借酒劲吻你 2021-01-30 18:56

The sample application on the android developers site validates the purchase json using java code. Has anybody had any luck working out how to validate the purchase in python.

3条回答
  •  抹茶落季
    2021-01-30 19:21

    Now that we're in 2016, here's how to do it with 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
    

提交回复
热议问题