Google Tink: How to get raw key string from a KeysetHandle?

2k Views Asked by At

I am new to Tink and would like to extract the raw key data(in String form) from KeysetHandle which I generated like this:

keysetHandle = KeysetHandle.generateNew(
                    AeadKeyTemplates.AES128_GCM);

Or maybe some other API to get it.

How can I achieve this?

3

There are 3 best solutions below

4
Thai Duong On

You can write the Keyset to disk with either KeysetHandle.write(), which requires encryption, other CleartextKeysetHandle.write(). Both require a BinaryKeysetWriter or JsonKeysetWriter.

0
Ursa Major On

Example will help. Here is how you would use CleartextKeysetHandle.write() to observe the key profile:

Try this for display:

    // display key [Caveat: ONLY for observation]
       public void display_key_profile_for_test_observation_only(KeysetHandle keysetHandle) throws IOException, GeneralSecurityException
       {
         System.out.println("\nDisplay key:");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        CleartextKeysetHandle.write(keysetHandle, JsonKeysetWriter.withOutputStream(outputStream));
        System.out.println("\n"+ new String(outputStream.toByteArray()));
       }

As this belongs to a class, you may have to do some slight code modification. You see the keyword this denoting that the code snippets come from a class. Here is the test usage:


       public void trial_usage_key_generation() throws IOException, GeneralSecurityException {

           for (CIPHER_SYMMETRIC_ALGOS algo_type : CIPHER_SYMMETRIC_ALGOS.values()) { 
               System.out.println("Generating key for : " + algo_type); 
               KeysetHandle keysetHandle = this.generate_key_for_test_observation_only(algo_type); 
               this.display_key_profile_for_test_observation_only(keysetHandle);
            }
       }
0
V.E.O On

You can use reflection to get the keyset as code below, or JsonKeysetWriter to get base64ed key bytestring (still needs to be unserialized to corresponding key object to get the raw key bytes).

        KeysetHandle keysetHandle = KeysetHandle.generateNew(
                AeadKeyTemplates.CHACHA20_POLY1305);

        Method method = keysetHandle.getClass().getDeclaredMethod("getKeyset");
        method.setAccessible(true);
        Keyset keyset = (Keyset) method.invoke(keysetHandle);
        ChaCha20Poly1305Key key = ChaCha20Poly1305Key.parseFrom(keyset.getKey(0).getKeyData().getValue());
        byte[] keyBytes = key.getKeyValue().toByteArray();