EncryptAES encrypts plaintext using AES-256-GCM. The nonce is prepended to the ciphertext and the result is encoded as base64 RawURL.
(key, text string)
| 29 | // EncryptAES encrypts plaintext using AES-256-GCM. The nonce is prepended to |
| 30 | // the ciphertext and the result is encoded as base64 RawURL. |
| 31 | func EncryptAES(key, text string) (string, error) { |
| 32 | keyBytes, err := deriveAESKey(key) |
| 33 | if err != nil { |
| 34 | return "", err |
| 35 | } |
| 36 | |
| 37 | block, err := aes.NewCipher(keyBytes) |
| 38 | if err != nil { |
| 39 | return "", err |
| 40 | } |
| 41 | |
| 42 | gcm, err := cipher.NewGCM(block) |
| 43 | if err != nil { |
| 44 | return "", err |
| 45 | } |
| 46 | |
| 47 | nonce := make([]byte, gcm.NonceSize()) |
| 48 | if _, err := io.ReadFull(rand.Reader, nonce); err != nil { |
| 49 | return "", err |
| 50 | } |
| 51 | |
| 52 | // Seal appends the encrypted and authenticated ciphertext to nonce. |
| 53 | ciphertext := gcm.Seal(nonce, nonce, []byte(text), nil) |
| 54 | return base64.RawURLEncoding.EncodeToString(ciphertext), nil |
| 55 | } |
| 56 | |
| 57 | // DecryptAES decrypts a base64 RawURL-encoded AES-256-GCM ciphertext produced |
| 58 | // by EncryptAES. Returns an error if authentication fails or input is malformed. |