Search code examples
goencryptiontink

Tink: Streaming encryption using Vault KMS


I'm trying to encrypt and decrypt using Tink and HashiCorp Vault. When I attempt to encrypt and decrypt within the same session using the same AEAD object, it works fine. However, if I store the result of the previous encryption run in a file and then try to run only the decryption function on this file, I encounter an error that says, "No matching key found for the ciphertext in the stream."

I've attached the code for reference:

keyUri := "hcvault://my-vault-url.com/transit/keys/my-key2"
vaultClient, err := hcvault.NewClient(keyUri, tlsConfig(), vaultToken())
if err != nil {
    log.Fatal(err)
}

kekAEAD, err := vaultClient.GetAEAD(keyUri)

if err != nil {
    log.Fatal(err)
}

// Generate a new keyset handle for the primitive we want to use.
newHandle, err := keyset.NewHandle(streamingaead.AES256GCMHKDF1MBKeyTemplate())
if err != nil {
    log.Fatal(err)
}

// Choose some associated data. This is the context in which the keyset will be used.
keysetAssociatedData := []byte("keyset encryption example")

// Encrypt the keyset with the KEK AEAD and the associated data.
buf := new(bytes.Buffer)
writer := keyset.NewBinaryWriter(buf)
err = newHandle.WriteWithAssociatedData(writer, kekAEAD, keysetAssociatedData)
if err != nil {
    log.Fatal(err)
}
encryptedKeyset := buf.Bytes()

reader := keyset.NewBinaryReader(bytes.NewReader(encryptedKeyset))
handle, err := keyset.ReadWithAssociatedData(reader, kekAEAD, keysetAssociatedData)
if err != nil {
    log.Fatal(err)
}

streamingAEAD, err := streamingaead.New(handle)
if err != nil {
    log.Fatal(err)
}
outputFilePath := "C:\\temp\\encryptionOutput6.txt"
inputFilePath := "C:\\temp\\input.mkv"

EncryptFile(streamingAEAD, inputFilePath, outputFilePath, keysetAssociatedData)
DecryptFile(streamingAEAD, outputFilePath, "c:\\temp\\f_result.mkv", keysetAssociatedData)

Solution

  • After conducting an investigation and receiving assistance from Tink developers, I found that Tink currently supports only Aead KEK URI. Therefore, if you intend to utilize a streaming mechanism, you need to store the keyset somewhere. For a comprehensive discussion, please refer to the following link: https://github.com/tink-crypto/tink-go/issues/8