Created
June 3, 2025 11:31
-
-
Save nnathan/69a4612cfb8ac29718d1966f1e1f9da8 to your computer and use it in GitHub Desktop.
Serialize an asymmetric keypair with Tink in cleartext and then load it back in
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# This is an example use of Tink Python Library | |
# to generate an asymmetric keypair, | |
# and write the private & public keyset | |
# to cleartext so that it can be saved | |
# to a file, which can then be read by another | |
# tink consuming program. | |
# | |
# There seems to be zilch examples of doing this. | |
import tink | |
import tink.hybrid | |
from tink import _secret_key_access | |
tink.hybrid.register() | |
key_template = ( | |
tink.hybrid.hybrid_key_templates.DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_AES_256_GCM | |
) | |
keyset_handle = tink.new_keyset_handle(key_template) | |
pub_keyset_handle = keyset_handle.public_keyset_handle() | |
keyset_json = tink.json_proto_keyset_format.serialize( | |
keyset_handle, _secret_key_access.TOKEN | |
) | |
pub_keyset_json = tink.json_proto_keyset_format.serialize( | |
pub_keyset_handle, _secret_key_access.TOKEN | |
) | |
print(keyset_json) | |
print(pub_keyset_json) | |
# example of loading the public/private keyset from a json | |
load_keyset_handle = tink.json_proto_keyset_format.parse( | |
keyset_json, _secret_key_access.TOKEN | |
) | |
load_pub_keyset_handle = tink.json_proto_keyset_format.parse( | |
pub_keyset_json, _secret_key_access.TOKEN | |
) | |
# Verify encrypt and decrypt works | |
from tink import hybrid | |
plaintext = b"decrypted your data..." | |
context = b"context" | |
hybrid.register() | |
hybrid_encrypt = pub_keyset_handle.primitive(hybrid.HybridEncrypt) | |
ciphertext = hybrid_encrypt.encrypt(plaintext, context) | |
print(ciphertext) | |
hybrid_decrypt = keyset_handle.primitive(hybrid.HybridDecrypt) | |
plaintext = hybrid_decrypt.decrypt(ciphertext, context) | |
print(plaintext) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment