github.com/trustbloc/kms-go@v1.1.2/crypto/tinkcrypto/primitive/composite/ecdh/subtle/ecdh_aes_aead_composite_encrypt.go (about)

     1  /*
     2  Copyright SecureKey Technologies Inc. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package subtle
     8  
     9  import (
    10  	"fmt"
    11  
    12  	"github.com/trustbloc/kms-go/crypto/tinkcrypto/primitive/composite"
    13  	"github.com/trustbloc/kms-go/crypto/tinkcrypto/primitive/composite/api"
    14  )
    15  
    16  // ECDHAEADCompositeEncrypt is an instance of ECDH-ES encryption with Concat KDF
    17  // and AEAD content encryption.
    18  type ECDHAEADCompositeEncrypt struct {
    19  	encHelper composite.EncrypterHelper
    20  	cek       []byte
    21  }
    22  
    23  var _ api.CompositeEncrypt = (*ECDHAEADCompositeEncrypt)(nil)
    24  
    25  // NewECDHAEADCompositeEncrypt returns ECDH (KW done outside of this Tink key implementation) AES encryption construct
    26  // for AEAD content encryption.
    27  func NewECDHAEADCompositeEncrypt(encHelper composite.EncrypterHelper, cek []byte) *ECDHAEADCompositeEncrypt {
    28  	return &ECDHAEADCompositeEncrypt{
    29  		encHelper: encHelper,
    30  		cek:       cek,
    31  	}
    32  }
    33  
    34  // Encrypt using composite ECDH with a Concat KDF key wrap and CBC+HMAC content encryption.
    35  func (e *ECDHAEADCompositeEncrypt) Encrypt(plaintext, aad []byte) ([]byte, error) {
    36  	if e.cek == nil {
    37  		return nil, fmt.Errorf("ecdhAEADCompositeEncrypt: missing cek")
    38  	}
    39  
    40  	aead, err := e.encHelper.GetAEAD(e.cek)
    41  	if err != nil {
    42  		return nil, err
    43  	}
    44  
    45  	ct, err := aead.Encrypt(plaintext, aad)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  
    50  	return e.encHelper.BuildEncData(ct)
    51  }