github.com/LagrangeDev/LagrangeGo@v0.0.0-20240512064304-ad4a85e10cb4/utils/crypto/aes.go (about) 1 package crypto 2 3 import ( 4 "crypto/aes" 5 "crypto/cipher" 6 "crypto/rand" 7 ) 8 9 func AESGCMEncrypt(data []byte, key []byte) ([]byte, error) { 10 nonce := make([]byte, 12) 11 if _, err := rand.Read(nonce); err != nil { 12 return nil, err 13 } 14 15 block, err := aes.NewCipher(key) 16 if err != nil { 17 return nil, err 18 } 19 aead, err := cipher.NewGCM(block) 20 if err != nil { 21 return nil, err 22 } 23 ciphertext := aead.Seal(nil, nonce, data, nil) 24 25 return append(nonce, ciphertext...), nil 26 } 27 28 func AESGCMDecrypt(data []byte, key []byte) ([]byte, error) { 29 nonce := data[:12] 30 ciphertext := data[12:] 31 32 block, err := aes.NewCipher(key) 33 if err != nil { 34 return nil, err 35 } 36 aead, err := cipher.NewGCM(block) 37 if err != nil { 38 return nil, err 39 } 40 plaintext, err := aead.Open(nil, nonce, ciphertext, nil) 41 if err != nil { 42 return nil, err 43 } 44 45 return plaintext, nil 46 }