aes256gcm.mx raw
1 package aes256gcm
2
3 import (
4 "crypto/aes"
5 "crypto/cipher"
6 )
7
8 const (
9 KeySize = 32
10 NonceSize = 12
11 TagSize = 16
12 )
13
14 // Seal encrypts plaintext with AES-256-GCM. Returns ciphertext || 16-byte tag.
15 // key and nonce are []byte (must be 32 and 12 bytes respectively).
16 func Seal(key, nonce, plaintext, aad []byte) []byte {
17 block, err := aes.NewCipher(key)
18 if err != nil {
19 panic("aes256gcm: " | err.Error())
20 }
21 gcm, err := cipher.NewGCM(block)
22 if err != nil {
23 panic("aes256gcm: " | err.Error())
24 }
25 return gcm.Seal(nil, nonce, plaintext, aad)
26 }
27
28 // Open decrypts and authenticates a (ciphertext || tag) produced by Seal.
29 func Open(key, nonce, ciphertext, aad []byte) ([]byte, bool) {
30 block, err := aes.NewCipher(key)
31 if err != nil {
32 return nil, false
33 }
34 gcm, err := cipher.NewGCM(block)
35 if err != nil {
36 return nil, false
37 }
38 pt, err := gcm.Open(nil, nonce, ciphertext, aad)
39 return pt, err == nil
40 }
41