tink icon indicating copy to clipboard operation
tink copied to clipboard

tinKey: Can we get examples for PRF implementation?

Open kushalhalder opened this issue 3 years ago • 1 comments

Please guide me to the right issue or doc if I have missed it.

kushalhalder avatar Mar 08 '22 13:03 kushalhalder

Hi @kushalhalder, You may create an encrypted keyset (encryption is optional but highly recommended https://developers.google.com/tink/generate-plaintext-keyset) that implements the PrfSet primitive:

tinkey create-keyset \
  --key-template HMAC_SHA256_PRF \
  --out-format json \
  --out encrypted_prf_keyset.json \
  --master-key-uri ... \
  --credentials ...

Then one can read the keyset, obtain a keyset handle and a primitive. E.g., in Python reading an unencrypted keyset:

  # Initialise Tink
  try:
    prf.register()
  except tink.TinkError as e:
    logging.error('Error initialising Tink: %s', e)
    return 1

  # Read the keyset into a keyset_handle
  with open(FLAGS.keyset_path, 'rt') as keyset_file:
    try:
      text = keyset_file.read()
      keyset_handle = cleartext_keyset_handle.read(tink.JsonKeysetReader(text))
    except tink.TinkError as e:
      logging.exception('Error reading key: %s', e)
      return 1

  # Get the primitive
  try:
    prfset_primitive = keyset_handle.primitive(prf.PrfSet)
  except tink.TinkError as e:
    logging.error('Error creating primitive: %s', e)
    return 1

  with open(some_input_path, 'rb') as input_file:
    input_data = input_file.read()
    output_data = prf_primitive.primary().compute(
        input_data, output_length=16)

An example for Python and AEAD: https://github.com/google/tink/tree/master/examples/python/encrypted_keyset. See also: https://github.com/google/tink/blob/master/docs/PRIMITIVES.md#pseudo-random-function-families.

Hope this helps!

morambro avatar May 02 '22 15:05 morambro