Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To perform AES encryption in Golang using the "global" cipher, you can follow the below steps:

  1. Import the "crypto/aes" and "crypto/cipher" packages:
import (
    "crypto/aes"
    "crypto/cipher"
)
  1. Create a key and an initialization vector (IV). The key should be 16, 24 or 32 bytes long to select AES-128, AES-192 or AES-256 respectively. The IV should be unique and random:
key := []byte("1234567890123456")
iv := []byte("1234567890123456")
  1. Create a new AES cipher block using the key:
block, err := aes.NewCipher(key)
if err != nil {
    // Handle error
}
  1. Create a new AES cipher block mode using the block and IV:
stream := cipher.NewCTR(block, iv)
  1. Encrypt the plaintext using the stream and put the result into a byte slice:
plaintext := []byte("Hello, world!")
ciphertext := make([]byte, len(plaintext))
stream.XORKeyStream(ciphertext, plaintext)

The complete code for AES encryption using the global cipher in Golang would look like this:

import (
    "crypto/aes"
    "crypto/cipher"
)

func main() {
    key := []byte("1234567890123456")
    iv := []byte("1234567890123456")

    block, err := aes.NewCipher(key)
    if err != nil {
        // Handle error
    }

    stream := cipher.NewCTR(block, iv)

    plaintext := []byte("Hello, world!")
    ciphertext := make([]byte, len(plaintext))

    stream.XORKeyStream(ciphertext, plaintext)

    // Do something with the ciphertext...
}