# How to decrypt Google Pay tokens using Python

Originally appeared on Medium (opens new window).

Google Pay provides a secure way for users to make payments using saved cards on Android phones. If you want to support Google Pay payments in your Android app, you would most likely want to use Google Pay’s Gateway Integration (opens new window) to process payments through a Payment Service Provider (PSP).

However, if your business is Payments Card Industry (PCI) Data Security Standard (DSS) Level 1 compliant, you might want to use the Direct Integration (opens new window) which will allow you to decrypt Google Pay tokens in your backend.

The Google Pay documentation describes (opens new window) the process of verifying and decrypting tokens. Google also developed a Java library, Tink (opens new window), which can be used (opens new window) to decrypt these tokens. We used the documentation and Tink to implement a Python package: google-pay-token-decryption (opens new window). In the rest of this article, we will describe how to use this package.

# 1. Install the google-pay-token-decryption package

You would need Python 3.8+ and pip to install the package:

pip install google-pay-token-decryption
1

# 2. Create an instance of GooglePayTokenDecryptor

To decrypt a token, you first need to set up a new instance of GooglePayTokenDecryptor:

from google_pay_token_decryption import GooglePayTokenDecryptor
decryptor = GooglePayTokenDecryptor(
    root_signing_keys,
    recipient_id,
    private_key
)
1
2
3
4
5
6

# 3. Decrypt the token

Now that you have an instance of GooglePayTokenDecryptor, you can decrypt a token using its decrypt_token method:

decrypted_token = decryptor.decrypt_token(encrypted_token)
1

encrypted_token is a Dict version of the encrypted JSON token you’ve received from your Android app. An example would look like this:

encrypted_token = {
    "signature": "MEYCIQCbtFh9UIf1Ty3NKZ2z0ZmL0SHwR30u...",
    "intermediateSigningKey": {
        "signedKey": "{\"keyValue\":\"MFkwEwYHKoZIzj0CAQYIIzj0D...\",\"keyExpiration\":\"1879409613939\"}",
        "signatures": [
            "MEQCIFBle+JsfsovRBeoFEYKWFAeBYFAhq0S+Gtu..."
        ]
    },
    "protocolVersion": "ECv2",
    "signedMessage": "{\"encryptedMessage\":\"PeYi+ZnJs1Gei1dSOkItd...",\"ephemeralPublicKey\":\"BD6pQKpy7yDebAX4q...",\"tag\":\"8gFteCvCuamX1RmL7OR..."}"
}
1
2
3
4
5
6
7
8
9
10
11

Google provides a test environment in which you can generate test tokens (opens new window) to test your implementation.

Newsletter

If you'd like to subscribe to my blog, please enter your details below. You can unsubscribe at any time.

Powered by Buttondown.

Last Updated: 11/20/2023, 10:04:51 AM