k8s.io/apiserver@v0.31.1/pkg/storage/value/encrypt/secretbox/secretbox.go (about)

     1  /*
     2  Copyright 2017 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  // Package secretbox transforms values for storage at rest using XSalsa20 and Poly1305.
    18  package secretbox
    19  
    20  import (
    21  	"context"
    22  	"crypto/rand"
    23  	"fmt"
    24  
    25  	"golang.org/x/crypto/nacl/secretbox"
    26  
    27  	"k8s.io/apiserver/pkg/storage/value"
    28  )
    29  
    30  // secretbox implements at rest encryption of the provided values given a 32 byte secret key.
    31  // Uses a standard 24 byte nonce (placed at the beginning of the cipher text) generated
    32  // from crypto/rand. Does not perform authentication of the data at rest.
    33  type secretboxTransformer struct {
    34  	key [32]byte
    35  }
    36  
    37  const nonceSize = 24
    38  
    39  // NewSecretboxTransformer takes the given key and performs encryption and decryption on the given
    40  // data.
    41  func NewSecretboxTransformer(key [32]byte) value.Transformer {
    42  	return &secretboxTransformer{key: key}
    43  }
    44  
    45  func (t *secretboxTransformer) TransformFromStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, bool, error) {
    46  	if len(data) < (secretbox.Overhead + nonceSize) {
    47  		return nil, false, fmt.Errorf("the stored data was shorter than the required size")
    48  	}
    49  	var nonce [nonceSize]byte
    50  	copy(nonce[:], data[:nonceSize])
    51  	data = data[nonceSize:]
    52  	out := make([]byte, 0, len(data)-secretbox.Overhead)
    53  	result, ok := secretbox.Open(out, data, &nonce, &t.key)
    54  	if !ok {
    55  		return nil, false, fmt.Errorf("output array was not large enough for encryption")
    56  	}
    57  	return result, false, nil
    58  }
    59  
    60  func (t *secretboxTransformer) TransformToStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, error) {
    61  	var nonce [nonceSize]byte
    62  	n, err := rand.Read(nonce[:])
    63  	if err != nil {
    64  		return nil, err
    65  	}
    66  	if n != nonceSize {
    67  		return nil, fmt.Errorf("unable to read sufficient random bytes")
    68  	}
    69  	return secretbox.Seal(nonce[:], data, &nonce, &t.key), nil
    70  }