Tink APIs take arbitrary binary blobs as input. This means that if you want to encrypt structured data, like protocol buffers, you need to encode the data first.
Encrypt a protobuf
To encrypt:
- Serialize the protobuf to a byte array.
- Encrypt the serialized bytes, then store or send the resulting ciphertext. Use:
To decrypt:
- Decrypt the ciphertext.
- If Step 1 was successful, deserialize the protobuf.
Protect a protobuf from tampering
In most cases, encrypting a protobuf is preferable to authentication alone.
To protect a protobuf from tampering:
- Serialize the protobuf to a byte array.
- Sign or authenticate the serialized bytes. Use:
- Store the serialized bytes together with the signature (or MAC).
To verify:
- Get the serialized protobuf and its signature (or MAC).
- Verify the signature (or MAC).
- Deserialize the protobuf.
Note that a valid signature or MAC does not guarantee that the data is correctly formatted. An implementation that parses the data should always expect that the data might be corrupt.
Protect multiple data items
To protect multiple data items, use a serialization method. Add all of the data items to a protobuf, and encrypt (or authenticate) it as described above.
You can also serialize as follows:
serialize(data1 , data2 , …, datan) = 4-byte-data1's length || data1 || 4-byte-data2's length || data2 || … || 4-byte-dataN's length || dataN
Finally, encrypt (or authenticate) the resulting byte array.