...

Source file src/k8s.io/kubernetes/cmd/kubeadm/app/util/crypto/crypto.go

Documentation: k8s.io/kubernetes/cmd/kubeadm/app/util/crypto

     1  /*
     2  Copyright 2019 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 crypto
    18  
    19  import (
    20  	"crypto/aes"
    21  	"crypto/cipher"
    22  	"crypto/rand"
    23  
    24  	"github.com/pkg/errors"
    25  )
    26  
    27  // CreateRandBytes returns a cryptographically secure slice of random bytes with a given size
    28  func CreateRandBytes(size uint32) ([]byte, error) {
    29  	bytes := make([]byte, size)
    30  	if _, err := rand.Read(bytes); err != nil {
    31  		return nil, err
    32  	}
    33  	return bytes, nil
    34  }
    35  
    36  // EncryptBytes takes a byte slice of raw data and an encryption key and returns an encrypted byte slice of data.
    37  // The key must be an AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256
    38  func EncryptBytes(data, key []byte) ([]byte, error) {
    39  	block, err := aes.NewCipher(key)
    40  	if err != nil {
    41  		return nil, err
    42  	}
    43  	gcm, err := cipher.NewGCM(block)
    44  	if err != nil {
    45  		return nil, err
    46  	}
    47  	nonce, err := CreateRandBytes(uint32(gcm.NonceSize()))
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  	return gcm.Seal(nonce, nonce, data, nil), nil
    52  }
    53  
    54  // DecryptBytes takes a byte slice of encrypted data and an encryption key and returns a decrypted byte slice of data.
    55  // The key must be an AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256
    56  func DecryptBytes(data, key []byte) ([]byte, error) {
    57  	block, err := aes.NewCipher(key)
    58  	if err != nil {
    59  		return nil, err
    60  	}
    61  	gcm, err := cipher.NewGCM(block)
    62  	if err != nil {
    63  		return nil, err
    64  	}
    65  	nonceSize := gcm.NonceSize()
    66  	if len(data) < nonceSize {
    67  		return nil, errors.New("size of data is less than the nonce")
    68  	}
    69  
    70  	nonce, out := data[:nonceSize], data[nonceSize:]
    71  	out, err = gcm.Open(nil, nonce, out, nil)
    72  	if err != nil {
    73  		return nil, err
    74  	}
    75  	return out, nil
    76  }
    77  

View as plain text