xref: /aosp_15_r20/external/tink/go/integration/gcpkms/gcp_kms_aead.go (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1// Copyright 2017 Google Inc.
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 gcpkms
18
19import (
20	"encoding/base64"
21
22	"google.golang.org/api/cloudkms/v1"
23
24	"github.com/google/tink/go/tink"
25)
26
27// gcpAEAD represents a GCP KMS service to a particular URI.
28type gcpAEAD struct {
29	keyURI string
30	kms    cloudkms.Service
31}
32
33var _ tink.AEAD = (*gcpAEAD)(nil)
34
35// newGCPAEAD returns a new GCP KMS service.
36func newGCPAEAD(keyURI string, kms *cloudkms.Service) tink.AEAD {
37	return &gcpAEAD{
38		keyURI: keyURI,
39		kms:    *kms,
40	}
41}
42
43// Encrypt encrypts the plaintext with associatedData.
44func (a *gcpAEAD) Encrypt(plaintext, associatedData []byte) ([]byte, error) {
45
46	req := &cloudkms.EncryptRequest{
47		Plaintext:                   base64.URLEncoding.EncodeToString(plaintext),
48		AdditionalAuthenticatedData: base64.URLEncoding.EncodeToString(associatedData),
49	}
50	resp, err := a.kms.Projects.Locations.KeyRings.CryptoKeys.Encrypt(a.keyURI, req).Do()
51	if err != nil {
52		return nil, err
53	}
54
55	return base64.StdEncoding.DecodeString(resp.Ciphertext)
56}
57
58// Decrypt decrypts ciphertext with with associatedData.
59func (a *gcpAEAD) Decrypt(ciphertext, associatedData []byte) ([]byte, error) {
60
61	req := &cloudkms.DecryptRequest{
62		Ciphertext:                  base64.URLEncoding.EncodeToString(ciphertext),
63		AdditionalAuthenticatedData: base64.URLEncoding.EncodeToString(associatedData),
64	}
65	resp, err := a.kms.Projects.Locations.KeyRings.CryptoKeys.Decrypt(a.keyURI, req).Do()
66	if err != nil {
67		return nil, err
68	}
69	return base64.StdEncoding.DecodeString(resp.Plaintext)
70}
71