github.com/zntrio/harp/v2@v2.0.9/pkg/sdk/value/encryption/dae/transformer.go (about)

     1  // Licensed to Elasticsearch B.V. under one or more contributor
     2  // license agreements. See the NOTICE file distributed with
     3  // this work for additional information regarding copyright
     4  // ownership. Elasticsearch B.V. licenses this file to you under
     5  // the Apache License, Version 2.0 (the "License"); you may
     6  // not use this file except in compliance with the License.
     7  // You may obtain a copy of the License at
     8  //
     9  //     http://www.apache.org/licenses/LICENSE-2.0
    10  //
    11  // Unless required by applicable law or agreed to in writing,
    12  // software distributed under the License is distributed on an
    13  // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    14  // KIND, either express or implied.  See the License for the
    15  // specific language governing permissions and limitations
    16  // under the License.
    17  
    18  package dae
    19  
    20  import (
    21  	"context"
    22  	"crypto/cipher"
    23  	"errors"
    24  	"fmt"
    25  
    26  	"github.com/zntrio/harp/v2/pkg/sdk/value/encryption"
    27  )
    28  
    29  // -----------------------------------------------------------------------------
    30  
    31  type daeTransformer struct {
    32  	aead             cipher.AEAD
    33  	nonceDeriverFunc NonceDeriverFunc
    34  }
    35  
    36  func (t *daeTransformer) To(ctx context.Context, input []byte) ([]byte, error) {
    37  	// Check input size
    38  	if len(input) > 64*1024*1024 {
    39  		return nil, errors.New("value too large")
    40  	}
    41  
    42  	// Derive nonce
    43  	nonce, err := t.nonceDeriverFunc(input, t.aead)
    44  	if err != nil {
    45  		return nil, fmt.Errorf("dae: unable to derive nonce: %w", err)
    46  	}
    47  	if len(nonce) != t.aead.NonceSize() {
    48  		return nil, errors.New("dae: derived nonce is too short")
    49  	}
    50  
    51  	// Retrieve additional data from context
    52  	aad, _ := encryption.AdditionalData(ctx)
    53  
    54  	// Seal the cleartext with deterministic nonce
    55  	cipherText := t.aead.Seal(nil, nonce, input, aad)
    56  
    57  	// Return encrypted value
    58  	return append(nonce, cipherText...), nil
    59  }
    60  
    61  func (t *daeTransformer) From(ctx context.Context, input []byte) ([]byte, error) {
    62  	// Check input size
    63  	if len(input) < t.aead.NonceSize() {
    64  		return nil, errors.New("dae: ciphered text too short")
    65  	}
    66  
    67  	nonce := input[:t.aead.NonceSize()]
    68  	text := input[t.aead.NonceSize():]
    69  	aad, _ := encryption.AdditionalData(ctx)
    70  
    71  	clearText, err := t.aead.Open(nil, nonce, text, aad)
    72  	if err != nil {
    73  		return nil, errors.New("failed to decrypt given message")
    74  	}
    75  
    76  	// No error
    77  	return clearText, nil
    78  }