xref: /aosp_15_r20/external/tink/go/keyderivation/keyderivation_test.go (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1// Copyright 2023 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15////////////////////////////////////////////////////////////////////////////////
16
17package keyderivation_test
18
19import (
20	"fmt"
21	"log"
22
23	"github.com/google/tink/go/aead"
24	"github.com/google/tink/go/keyderivation"
25	"github.com/google/tink/go/keyset"
26	"github.com/google/tink/go/prf"
27)
28
29func Example() {
30	template, err := keyderivation.CreatePRFBasedKeyTemplate(prf.HKDFSHA256PRFKeyTemplate(), aead.AES128GCMKeyTemplate())
31	if err != nil {
32		log.Fatal(err)
33	}
34
35	handle, err := keyset.NewHandle(template)
36	if err != nil {
37		log.Fatal(err)
38	}
39
40	deriver, err := keyderivation.New(handle)
41	if err != nil {
42		log.Fatal(err)
43	}
44
45	derivedHandle, err := deriver.DeriveKeyset([]byte("salt"))
46	if err != nil {
47		log.Fatal(err)
48	}
49
50	// Use the derived keyset.
51	a, err := aead.New(derivedHandle)
52	if err != nil {
53		log.Fatal(err)
54	}
55
56	ciphertext, err := a.Encrypt([]byte("a secret message"), nil)
57	if err != nil {
58		log.Fatal(err)
59	}
60
61	plaintext, err := a.Decrypt(ciphertext, nil)
62	if err != nil {
63		log.Fatal(err)
64	}
65
66	fmt.Println(string(plaintext))
67	// Output: a secret message
68}
69