Skip to content

Instantly share code, notes, and snippets.

@alex-ant
Created September 6, 2021 15:36
Show Gist options
  • Save alex-ant/14b309d615f163514f73536832d85b8b to your computer and use it in GitHub Desktop.
Save alex-ant/14b309d615f163514f73536832d85b8b to your computer and use it in GitHub Desktop.
Encrypt data with AES-256
package encryption
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"fmt"
"io"
)
// Encrypt encrypts the data using the 256-bit key.
func Encrypt(key, data []byte) ([]byte, error) {
if len(key) != 32 {
return nil, errors.New("key must be 32 bytes long")
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("failed to create AES cipher: %v", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("failed to create GCM: %v", err)
}
nonce := make([]byte, gcm.NonceSize())
_, err = io.ReadFull(rand.Reader, nonce)
if err != nil {
return nil, fmt.Errorf("failed to read into nonce: %v", err)
}
res := gcm.Seal(nonce, nonce, data, nil)
return res, nil
}
// Decrypt decrypts the data using the 256-bit key.
func Decrypt(key, data []byte) ([]byte, error) {
if len(key) != 32 {
return nil, errors.New("key must be 32 bytes long")
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("failed to create AES cipher: %v", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("failed to create GCM: %v", err)
}
nonceSize := gcm.NonceSize()
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
res, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, fmt.Errorf("failed to decrypt: %v", err)
}
return res, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment