github.com/zntrio/harp/v2@v2.0.9/pkg/sdk/value/encryption/paseto/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 paseto
    19  
    20  import (
    21  	"context"
    22  	"crypto/rand"
    23  	"encoding/base64"
    24  	"fmt"
    25  	"strings"
    26  
    27  	"github.com/zntrio/harp/v2/build/fips"
    28  	pasetov4 "github.com/zntrio/harp/v2/pkg/sdk/security/crypto/paseto/v4"
    29  	"github.com/zntrio/harp/v2/pkg/sdk/value"
    30  	"github.com/zntrio/harp/v2/pkg/sdk/value/encryption"
    31  )
    32  
    33  func init() {
    34  	if !fips.Enabled() {
    35  		encryption.Register("paseto", Transformer)
    36  	}
    37  }
    38  
    39  func Transformer(key string) (value.Transformer, error) {
    40  	// Remove the prefix
    41  	key = strings.TrimPrefix(key, "paseto:")
    42  
    43  	// Decode key
    44  	k, err := base64.URLEncoding.DecodeString(key)
    45  	if err != nil {
    46  		return nil, fmt.Errorf("paseto: unable to decode key: %w", err)
    47  	}
    48  	if l := len(k); l != pasetov4.KeyLength {
    49  		return nil, fmt.Errorf("paseto: invalid secret key length (%d)", l)
    50  	}
    51  
    52  	// Copy secret key
    53  	var secretKey [pasetov4.KeyLength]byte
    54  	copy(secretKey[:], k)
    55  
    56  	return &pasetoTransformer{
    57  		key: secretKey,
    58  	}, nil
    59  }
    60  
    61  // -----------------------------------------------------------------------------
    62  
    63  type pasetoTransformer struct {
    64  	key [pasetov4.KeyLength]byte
    65  }
    66  
    67  func (d *pasetoTransformer) From(_ context.Context, input []byte) ([]byte, error) {
    68  	return pasetov4.Decrypt(d.key[:], input, "", "")
    69  }
    70  
    71  func (d *pasetoTransformer) To(_ context.Context, input []byte) ([]byte, error) {
    72  	// Encrypt with paseto v4.local
    73  	return pasetov4.Encrypt(rand.Reader, d.key[:], input, "", "")
    74  }