In Go, you can use the crypto/cipher
and crypto/aes
packages to encrypt and decrypt data using the AES symmetric encryption algorithm. Here's an example of how you can encode and decode data for secure communication:
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"io"
)
func generateRandomKey() []byte {
key := make([]byte, 32) // AES-256
if _, err := rand.Read(key); err != nil {
panic(err)
}
return key
}
func encrypt(data []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ciphertext := make([]byte, aes.BlockSize+len(data))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(ciphertext[aes.BlockSize:], data)
return ciphertext, nil
}
func decrypt(ciphertext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(ciphertext) < aes.BlockSize {
return nil, errors.New("ciphertext too short")
}
iv := ciphertext[:aes.BlockSize]
data := ciphertext[aes.BlockSize:]
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(data, data)
return data, nil
}
func main() {
// Generate a random AES key
key := generateRandomKey()
// Encode data
message := "Hello, World!"
encoded := base64.StdEncoding.EncodeToString([]byte(message))
// Encrypt the encoded data
ciphertext, err := encrypt([]byte(encoded), key)
if err != nil {
panic(err)
}
// Transmit the encrypted data...
// Decrypt the received data
decrypted, err := decrypt(ciphertext, key)
if err != nil {
panic(err)
}
// Decode the decrypted data
decoded, err := base64.StdEncoding.DecodeString(string(decrypted))
if err != nil {
panic(err)
}
// Print the original message
fmt.Println(string(decoded))
}
Make sure to handle errors appropriately in your code. Also, note that this example uses the AES-CTR mode of operations, but you can choose a different mode depending on your requirements.