package main import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/hex" "fmt" "io" ) func getKey(key []byte) (string,error) { bytes := make([]byte, 32) //generate a random 32 byte key for AES-256 if _, err := rand.Read(bytes); err != nil { return "", err } return hex.EncodeToString(bytes),nil } func encrypt(text string, keytext string) (string, error) { key, _ := hex.DecodeString(keytext) plaintext := []byte(text) block, err := aes.NewCipher(key) if err != nil { return "",err } //GCM - https://en.wikipedia.org/wiki/Galois/Counter_Mode //https://golang.org/pkg/crypto/cipher/#NewGCM aesGCM, err := cipher.NewGCM(block) if err != nil { return "",err } nonce := make([]byte, aesGCM.NonceSize()) if _, err = io.ReadFull(rand.Reader, nonce); err != nil { return "",err } //Encrypt the data using aesGCM.Seal //Since we don't want to save the nonce somewhere else in this case, we add it as a prefix to the encrypted data. The first nonce argument in Seal is the prefix. ciphertext := aesGCM.Seal(nonce, nonce, plaintext, nil) return fmt.Sprintf("%x", ciphertext),nil } func decrypt(encodedtext string, keytext string) (string,error) { key, _ := hex.DecodeString(keytext) enc, _ := hex.DecodeString(encodedtext) block, err := aes.NewCipher(key) if err != nil { return "",err } aesGCM, err := cipher.NewGCM(block) if err != nil { return "",err } nonceSize := aesGCM.NonceSize() //Extract the nonce from the encrypted data nonce, ciphertext := enc[:nonceSize], enc[nonceSize:] //Decrypt the data text, err := aesGCM.Open(nil, nonce, ciphertext, nil) if err != nil { return "",err } return fmt.Sprintf("%s", text), nil }