How to encrypt data using symmetric key cryptography in Go?

To encrypt data using symmetric key cryptography in Go, you can use the crypto/cipher package along with a symmetric encryption algorithm like AES.

Here is an example of how you can encrypt data using a symmetric key:

package main import ( "crypto/aes" "crypto/cipher" "crypto/rand" "fmt" "io" ) func main() { // Generate a random symmetric key key := make([]byte, 32) _, err := rand.Read(key) if err != nil { panic(err) } // Data to be encrypted data := []byte("Hello, World!") // Create a new AES block cipher with the key block, err := aes.NewCipher(key) if err != nil { panic(err) } // Generate a new random initialization vector iv := make([]byte, aes.BlockSize) _, err = rand.Read(iv) if err != nil { panic(err) } // Create a new AES block mode cipher using the block and iv mode := cipher.NewCBCEncrypter(block, iv) // Create a buffer to hold the encrypted data encrypted := make([]byte, len(data)) // Encrypt the data mode.CryptBlocks(encrypted, data) // Print the encrypted data and the initialization vector fmt.Printf("Encrypted: %x\n", encrypted) fmt.Printf("IV: %x\n", iv) }

In this example, we generate a random symmetric key using rand.Read. We then create an AES block cipher with the key and generate a random initialization vector (iv). Next, we create a new AES block mode cipher using the block and iv. Finally, we encrypt the data using the CryptBlocks method and print the encrypted data along with the iv.

Note: This example demonstrates how to encrypt data using AES in CBC (Cipher Block Chaining) mode. You can explore other symmetric key encryption algorithms and modes supported by the crypto/cipher package for different use cases.