github.com/zntrio/harp/v2@v2.0.9/pkg/sdk/value/encryption/fernet/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 fernet
    19  
    20  import (
    21  	"context"
    22  	"errors"
    23  	"fmt"
    24  	"strings"
    25  
    26  	"github.com/fernet/fernet-go"
    27  
    28  	"github.com/zntrio/harp/v2/pkg/sdk/value"
    29  	"github.com/zntrio/harp/v2/pkg/sdk/value/encryption"
    30  )
    31  
    32  func init() {
    33  	encryption.Register("fernet", Transformer)
    34  }
    35  
    36  // Transformer returns a fernet encryption transformer.
    37  func Transformer(key string) (value.Transformer, error) {
    38  	// Remove the prefix
    39  	key = strings.TrimPrefix(key, "fernet:")
    40  
    41  	// Check given keys
    42  	k, err := fernet.DecodeKey(key)
    43  	if err != nil {
    44  		return nil, fmt.Errorf("fernet: unable to initialize fernet transformer: %w", err)
    45  	}
    46  
    47  	// Return decorator constructor
    48  	return &fernetTransformer{
    49  		key: k,
    50  	}, nil
    51  }
    52  
    53  // -----------------------------------------------------------------------------
    54  
    55  type fernetTransformer struct {
    56  	key *fernet.Key
    57  }
    58  
    59  func (d *fernetTransformer) To(_ context.Context, input []byte) ([]byte, error) {
    60  	// Encrypt value
    61  	out, err := fernet.EncryptAndSign(input, d.key)
    62  	if err != nil {
    63  		return nil, fmt.Errorf("fernet: unable to transform input value: %w", err)
    64  	}
    65  
    66  	// No error
    67  	return out, nil
    68  }
    69  
    70  func (d *fernetTransformer) From(_ context.Context, input []byte) ([]byte, error) {
    71  	// Encrypt value
    72  	out := fernet.VerifyAndDecrypt(input, 0, []*fernet.Key{d.key})
    73  	if out == nil {
    74  		return nil, errors.New("fernet: unable to decrypt value")
    75  	}
    76  
    77  	// No error
    78  	return out, nil
    79  }