0

I find the snippet of the code from https://stackoverflow.com/questions/24072026/golang-aes-ecb-encryption/71614065?noredirect=1#comment126568172_71614065in golang to decrypts AES-128 data in ECB (note that the block size is 16 bytes):

package main

import (
    "crypto/aes"
)

func DecryptAes128Ecb(data, key []byte) []byte {
    cipher, _ := aes.NewCipher([]byte(key))
    decrypted := make([]byte, len(data))
    size := 16

    for bs, be := 0, size; bs < len(data); bs, be = bs+size, be+size {
        cipher.Decrypt(decrypted[bs:be], data[bs:be])
    }

    return decrypted
}
  • But I am unable to understand it. I tried to search full code online but I no luck.
  • Can someone provide the full code or explain it.
  • Sorry, I am new to golang

I tried to search online but was unable to get the full code and understand it.

random_i
  • 1
  • 1
  • 1

1 Answers1

0

First, keep in mind that ECB is insecure and must not be used for real encryption. That being said, here is what the code does line by line:

cipher, _ := aes.NewCipher([]byte(key))

This returns a new object which has methods to perform AES encryption/decryption, using the given key.

decrypted := make([]byte, len(data))

This allocates space to hold the decrypted result. The length is the same as the length of the input.

size := 16

This is the block size of the AES cipher in bytes. We could also have written size := cipher.BlockSize() here. The length of the input must be a multiple of 16 bytes.

for bs, be := 0, size; bs < len(data); bs, be = bs+size, be+size { ... }

This iterates over the 16 byte blocks in the input. The first block has start bs = 0 and end be = size, and the we just add 16 to both bs and be repeatedly to get all the other blocks.

cipher.Decrypt(decrypted[bs:be], data[bs:be])

This uses the cipher object we created at the start to decrypt a single block. The input is data[bs:be] and the output is stored in decrypted[bs:be]. After the loop is finished, the slice decrypted contains the decrypted cleartext.

jochen
  • 3,728
  • 2
  • 39
  • 49