Skip to content

Instantly share code, notes, and snippets.

@yaliv
Last active March 21, 2022 02:10
Show Gist options
  • Save yaliv/7eb67f73c801f751abb0dbc189759e74 to your computer and use it in GitHub Desktop.
Save yaliv/7eb67f73c801f751abb0dbc189759e74 to your computer and use it in GitHub Desktop.
AES encryption + AAD
package aesutil
import (
"crypto/aes"
"crypto/cipher"
crypto_rand "crypto/rand"
"errors"
)
const (
KeySize = 32
IVSize = 12
)
func Encrypt(key, plaintext, additionalData []byte) ([]byte, error) {
if len(key) != KeySize {
return nil, errors.New("invalid key length")
}
iv := make([]byte, IVSize)
_, err := crypto_rand.Read(iv)
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
ciphertextCombo := aesgcm.Seal(iv, iv, plaintext, additionalData)
return ciphertextCombo, nil
}
func Decrypt(key, ciphertextCombo, additionalData []byte) ([]byte, error) {
if len(key) != KeySize {
return nil, errors.New("invalid key length")
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
ivSize := aesgcm.NonceSize()
iv, ciphertext := ciphertextCombo[:ivSize], ciphertextCombo[ivSize:]
plaintext, err := aesgcm.Open(nil, iv, ciphertext, additionalData)
if err != nil {
return nil, err
}
return plaintext, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment