golang encrypt example

To encrypt a string in Go (Golang), you can use the crypto/aes package. Here is an example with explanations for each step:

package main

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "encoding/base64"
    "fmt"
    "io"
)

func main() {
    // The string to be encrypted
    plaintext := []byte("This is the secret message")

    // Generate a random 32-byte key
    key := make([]byte, 32)
    if _, err := io.ReadFull(rand.Reader, key); err != nil {
        panic(err)
    }

    // Create a new AES cipher block using the key
    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err)
    }

    // Generate a random IV (initialization vector)
    iv := make([]byte, aes.BlockSize)
    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
        panic(err)
    }

    // Create a new AES cipher in CBC mode with the block and IV
    mode := cipher.NewCBCEncrypter(block, iv)

    // Pad the plaintext to a multiple of the block size
    paddedPlaintext := pad(plaintext, aes.BlockSize)

    // Create a byte slice to hold the ciphertext
    ciphertext := make([]byte, len(paddedPlaintext))

    // Encrypt the padded plaintext
    mode.CryptBlocks(ciphertext, paddedPlaintext)

    // Encode the ciphertext in base64
    encodedCiphertext := base64.StdEncoding.EncodeToString(ciphertext)

    // Print the encoded ciphertext
    fmt.Println(encodedCiphertext)
}

// Pad the input to a multiple of the block size
func pad(input []byte, blockSize int) []byte {
    padding := blockSize - (len(input) % blockSize)
    padText := bytes.Repeat([]byte{byte(padding)}, padding)
    return append(input, padText...)
}

Explanation:

  1. Import the necessary packages: crypto/aes, crypto/cipher, crypto/rand, encoding/base64, fmt, and io.

  2. Define the plaintext message that you want to encrypt.

  3. Generate a random 32-byte key using the io.ReadFull function.

  4. Create a new AES cipher block using the generated key.

  5. Generate a random IV (initialization vector) using the io.ReadFull function.

  6. Create a new AES cipher in CBC (Cipher Block Chaining) mode with the block and IV.

  7. Pad the plaintext to a multiple of the block size using the pad function. Padding ensures that the plaintext can be divided into blocks for encryption.

  8. Create a byte slice to hold the ciphertext.

  9. Encrypt the padded plaintext using the mode.CryptBlocks function.

  10. Encode the ciphertext in base64 using the base64.StdEncoding.EncodeToString function.

  11. Print the encoded ciphertext.

  12. Define the pad function, which pads the input to a multiple of the block size. The padding value is equal to the number of padding bytes added.

Note that this example demonstrates basic encryption using AES in CBC mode. It is important to note that encryption is a complex topic, and it is recommended to use secure and well-tested encryption libraries in real-world scenarios.