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

     1  package aead
     2  
     3  import (
     4  	"crypto/aes"
     5  	"crypto/cipher"
     6  
     7  	"git.sr.ht/~pingoo/stdx/crypto"
     8  )
     9  
    10  const (
    11  	// Aes256GcmKeySize is the size of the key used by the AES-256-GCM AEAD, in bytes.
    12  	Aes256GcmKeySize = crypto.Size256
    13  
    14  	// Aes256GcmNonceSize is the size of the nonce used with the AES-256-GCM
    15  	// variant of this AEAD, in bytes.
    16  	Aes256GcmNonceSize = crypto.Size96
    17  )
    18  
    19  // NewAes256GcmKey generates a new random secret key.
    20  func NewAes256GcmKey() ([]byte, error) {
    21  	return crypto.RandBytes(Aes256GcmKeySize)
    22  }
    23  
    24  // NewAes256GcmKey generates a new random nonce.
    25  func NewAes256GcmNonce() ([]byte, error) {
    26  	return crypto.RandBytes(Aes256GcmNonceSize)
    27  }
    28  
    29  // NewAEAD returns a AES-256-GCM AEAD that uses the given 256-bit key.
    30  func NewAes256Gcm(key []byte) (aeadCipher cipher.AEAD, err error) {
    31  	blockCipher, err := aes.NewCipher(key)
    32  	if err != nil {
    33  		return
    34  	}
    35  
    36  	aeadCipher, err = cipher.NewGCM(blockCipher)
    37  	if err != nil {
    38  		return
    39  	}
    40  	return
    41  }