Python Encryption Using Tink

February 23, 2021

Why use Tink

  • Easy to use correctly for newbie (avoid crypto mistakes)
  • Support for Java/Android, C++, Obj-C, Go, and Python (Javascript/Typescript is in an alpha state)

Setup and Code

This sample will use symmetric key encryption (encrypting the same data will generate different ciphertext).

Depedencies

pip install tink

Tinkey

You use Tinkey to generate Tink keysets (secret key).

Install

wget https://storage.googleapis.com/tinkey/tinkey-1.5.0.tar.gz
tar zxvf tinkey-1.5.0.tar.gz 
./tinkey

Generate keyset

./tinkey create-keyset --key-template AES256_GCM --out secret/tink-keyset.json

Code

secret.py

import tink
from tink import cleartext_keyset_handle

TINK_KEYSET = 'secret/tink-keyset.json'
with open(TINK_KEYSET, 'r') as f:
    json_keyset = f.read()
reader = tink.JsonKeysetReader(json_keyset)
# keyset_handle = tink.read_keyset_handle(reader, master_key_aead) # 
tink_keyset_handle = cleartext_keyset_handle.read(reader)

test.py

from tink import aead
from secret import tink_keyset_handle as keyset_handle
aead.register()
aead_primitive = keyset_handle.primitive(aead.Aead)

plaintext = b'Hello World'
associated_data = b'verify'

ciphertext = aead_primitive.encrypt(plaintext, associated_data)
print(ciphertext)

text = aead_primitive.decrypt(ciphertext, associated_data)
print(text)

NOTE: Python 3: Byte, Str and Unicode

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.