git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/crypto/aead/encrypt.go (about)

     1  package aead
     2  
     3  import (
     4  	"crypto/cipher"
     5  	"errors"
     6  
     7  	"git.sr.ht/~pingoo/stdx/crypto"
     8  )
     9  
    10  // Encrypt is an helper function to symetrically encrypt a piece of data using AES-256-GCM
    11  // returning the nonce separatly
    12  func EncryptWithNonce(key, plaintext, additionalData []byte) (ciphertext, nonce []byte, err error) {
    13  	nonce, err = NewAes256GcmNonce()
    14  	if err != nil {
    15  		return
    16  	}
    17  
    18  	cipher, err := NewAes256Gcm(key)
    19  	if err != nil {
    20  		return
    21  	}
    22  
    23  	ciphertext = cipher.Seal(nil, nonce, plaintext, additionalData)
    24  	return
    25  }
    26  
    27  // DecryptWithNonce is an helper function to symetrically  decrypt a piece of data using AES-256-GCM
    28  // taking the nonce as a separate piece of input
    29  func DecryptWithNonce(key, nonce, ciphertext, additionalData []byte) (plaintext []byte, err error) {
    30  	cipher, err := NewAes256Gcm(key)
    31  	if err != nil {
    32  		return
    33  	}
    34  
    35  	plaintext, err = cipher.Open(nil, nonce, ciphertext, additionalData)
    36  	return
    37  }
    38  
    39  // Encrypt is an helper function to symetrically encrypt a piece of data using the given cipher
    40  // the nonce is prepended to the ciphertext in the returned buffer
    41  func Encrypt(cipher cipher.AEAD, key, plaintext, additionalData []byte) (ciphertext []byte, err error) {
    42  	nonce, err := crypto.RandBytes(uint64(cipher.NonceSize()))
    43  	if err != nil {
    44  		return
    45  	}
    46  
    47  	ciphertext = cipher.Seal(nil, nonce, plaintext, additionalData)
    48  	ciphertext = append(nonce, ciphertext...)
    49  	return
    50  }
    51  
    52  // DecryptWithNonce is an helper function to symetrically decrypt a piece of data using the provided cipher
    53  // The nonce should be at the begining of the ciphertext
    54  func Decrypt(cipher cipher.AEAD, key, ciphertext, additionalData []byte) (plaintext []byte, err error) {
    55  	nonceSize := cipher.NonceSize()
    56  
    57  	if len(ciphertext) < nonceSize {
    58  		err = errors.New("crypto.Decrypt: len(ciphertext) < NonceSize")
    59  		return
    60  	}
    61  
    62  	nonce := ciphertext[:nonceSize]
    63  	ciphertext = ciphertext[nonceSize:]
    64  
    65  	plaintext, err = cipher.Open(nil, nonce, ciphertext, additionalData)
    66  	return
    67  }