github.com/argoproj/argo-cd/v3@v3.2.1/util/crypto/crypto.go (about)

     1  package crypto
     2  
     3  import (
     4  	"crypto/aes"
     5  	"crypto/cipher"
     6  	"crypto/rand"
     7  	"crypto/sha256"
     8  	"errors"
     9  	"io"
    10  
    11  	"golang.org/x/crypto/scrypt"
    12  )
    13  
    14  // KeyFromPassphrase generates 32 byte key from the passphrase
    15  func KeyFromPassphrase(passphrase string) ([]byte, error) {
    16  	// salt is just a hash of a passphrase (effectively no salt)
    17  	salt := sha256.Sum256([]byte(passphrase))
    18  	// These defaults will consume approximately 16MB of memory (128 * r * N)
    19  	const N = 16384
    20  	const r = 8
    21  	return scrypt.Key([]byte(passphrase), salt[:], N, r, 1, 32)
    22  }
    23  
    24  // Encrypt encrypts the given data with the given passphrase.
    25  func Encrypt(data []byte, key []byte) ([]byte, error) {
    26  	block, err := aes.NewCipher(key)
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  	gcm, err := cipher.NewGCM(block)
    31  	if err != nil {
    32  		return nil, err
    33  	}
    34  	nonce := make([]byte, gcm.NonceSize())
    35  	if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
    36  		return nil, err
    37  	}
    38  	ciphertext := gcm.Seal(nonce, nonce, data, nil)
    39  	return ciphertext, nil
    40  }
    41  
    42  // Decrypt decrypts the given data using the given passphrase.
    43  func Decrypt(data []byte, key []byte) ([]byte, error) {
    44  	block, err := aes.NewCipher(key)
    45  	if err != nil {
    46  		return nil, err
    47  	}
    48  	gcm, err := cipher.NewGCM(block)
    49  	if err != nil {
    50  		return nil, err
    51  	}
    52  	nonceSize := gcm.NonceSize()
    53  	if len(data) < nonceSize {
    54  		return nil, errors.New("data length is less than nonce size")
    55  	}
    56  	nonce, ciphertext := data[:nonceSize], data[nonceSize:]
    57  	plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
    58  	if err != nil {
    59  		return nil, err
    60  	}
    61  	return plaintext, nil
    62  }