Ask Your Question
3

How to perform AES encryption in Golang using the "global" cipher?

asked 2023-07-13 20:45:48 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-13 21:09:02 +0000

bukephalos gravatar image

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...
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-13 20:45:48 +0000

Seen: 12 times

Last updated: Jul 13 '23