Tink Python Cryptography Library

1.14.1 · active · verified Fri Apr 10

Tink is a multi-language, cross-platform library that provides cryptographic APIs designed to be secure, easy to use, and hard to misuse. It is developed by cryptographers and security engineers at Google and offers primitives for common cryptographic tasks like AEAD, Streaming AEAD, Deterministic AEAD, MAC, Hybrid Encryption, Digital Signatures, and JWT. The library is actively maintained with frequent releases, currently at version 1.14.1.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic Authenticated Encryption with Associated Data (AEAD) using Tink. It covers initializing Tink, generating a new keyset, encrypting and decrypting data, and a warning-laden example of parsing a cleartext keyset. This example is simplified and does not involve KMS for brevity, but the same primitive concept applies.

import tink
from tink import aead
from tink import tink_config
from tink import secret_key_access
from tink.json_proto_keyset_format import parse

def main():
    # 1. Initialize Tink with all standard primitives.
    tink_config.register()

    # 2. Create a new AEAD keyset handle from a key template.
    # WARNING: Using cleartext keysets directly in code is a security risk.
    # For production, use secure key management, e.g., KMS or encrypted keysets.
    key_template = aead.aead_key_templates.AES256_GCM
    keyset_handle = tink.new_keyset_handle(key_template)

    # 3. Obtain the AEAD primitive from the keyset handle.
    aead_primitive = keyset_handle.primitive(aead.Aead)

    # 4. Define plaintext and associated data.
    plaintext = b'This is some secret data.'
    associated_data = b'associated_data_for_encryption'

    # 5. Encrypt the data.
    ciphertext = aead_primitive.encrypt(plaintext, associated_data)
    print(f'Encrypted data: {ciphertext.hex()}')

    # 6. Decrypt the data.
    try:
        decrypted_data = aead_primitive.decrypt(ciphertext, associated_data)
        print(f'Decrypted data: {decrypted_data.decode()}')
        assert decrypted_data == plaintext
        print('Encryption and decryption successful!')
    except tink.TinkError as e:
        print(f'Decryption failed: {e}')

    # Example of loading a cleartext keyset (for demonstration only, not recommended for production)
    cleartext_keyset_json = '{\"primaryKeyId\":1919301694,\"key\":[{\"keyData\":{\"typeUrl\":\"type.googleapis.com/google.crypto.tink.AesGcmKey\",\"value\":\"EhDKd0x8s2g+tXf1nJjDqD8u\",\"keyMaterialType\":\"SYMMETRIC\"},\"status\":\"ENABLED\",\"keyId\":1919301694,\"outputPrefixType\":\"TINK\"}]}'
    try:
        loaded_keyset_handle = parse(cleartext_keyset_json, secret_key_access.TOKEN)
        print("Successfully loaded cleartext keyset (for demonstration).")
    except tink.TinkError as e:
        print(f"Failed to load cleartext keyset: {e}")

if __name__ == '__main__':
    main()

view raw JSON →