Last active
March 21, 2022 02:10
-
-
Save yaliv/7eb67f73c801f751abb0dbc189759e74 to your computer and use it in GitHub Desktop.
AES encryption + AAD
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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