Python Encryption Using Tink

Feb 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.gztar 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 tinkfrom tink import cleartext_keyset_handleTINK_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 aeadfrom secret import tink_keyset_handle as keyset_handleaead.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:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.