github.com/pf-qiu/concourse/v6@v6.7.3-0.20201207032516-1f455d73275f/atc/db/encryption/encryption_key.go (about)

     1  package encryption
     2  
     3  import (
     4  	"crypto/cipher"
     5  	"crypto/rand"
     6  	"encoding/hex"
     7  	"io"
     8  )
     9  
    10  type Key struct {
    11  	aesgcm cipher.AEAD
    12  }
    13  
    14  func NewKey(a cipher.AEAD) *Key {
    15  	return &Key{
    16  		aesgcm: a,
    17  	}
    18  }
    19  
    20  func (e Key) Encrypt(plaintext []byte) (string, *string, error) {
    21  	nonce := make([]byte, 12)
    22  	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
    23  		return "", nil, err
    24  	}
    25  
    26  	ciphertext := e.aesgcm.Seal(nil, nonce, plaintext, nil)
    27  
    28  	noncense := hex.EncodeToString(nonce)
    29  
    30  	return hex.EncodeToString(ciphertext), &noncense, nil
    31  }
    32  
    33  func (e Key) Decrypt(text string, n *string) ([]byte, error) {
    34  	if n == nil {
    35  		return nil, ErrDataIsNotEncrypted
    36  	}
    37  
    38  	ciphertext, err := hex.DecodeString(text)
    39  	if err != nil {
    40  		return nil, err
    41  	}
    42  
    43  	nonce, err := hex.DecodeString(*n)
    44  	if err != nil {
    45  		return nil, err
    46  	}
    47  
    48  	plaintext, err := e.aesgcm.Open(nil, nonce, ciphertext, nil)
    49  	if err != nil {
    50  		return nil, err
    51  	}
    52  
    53  	return plaintext, nil
    54  }