Why am I getting an index out of range error when base64 encodes an array of bytes?

When encoding a byte array into a base64 byte array, the code below creates a runtime error index out of range. How can this be solved?

package main

import (
    "fmt"
    "encoding/base64"
)

func main() {
    data := []byte("string of data")
    var encodedData []byte
    base64.StdEncoding.Encode(encodedData, data)
    fmt.Println(encodedData)
}

Playground here

+4
source share
3 answers

Error:

panic: runtime error: index out of range

goroutine 1 [running]:
encoding/base64.(*Encoding).Encode(0xc420056000, 0x0, 0x0, 0x0, 0xc42003bf30, 0xe, 0x20)
        /usr/lib/go/src/encoding/base64/base64.go:113 +0x27b
main.main()
        /home/martin/a.go:11 +0x9b
exit status 2

shell returned 1

If we look at line /usr/lib/go/src/encoding/base64/base64.go113, we will see (abbreviated):

n := (len(src) / 3) * 3
for si < n {
    // [..]
    dst[di+0] = enc.encode[val>>18&0x3F]
    dst[di+0] = enc.encode[val>>18&0x3F]
    dst[di+1] = enc.encode[val>>12&0x3F]
    // [..]
}

In other words, this function sets the index directly dst. The length var encodedData []byteis zero, so you get an error index out of range.

One way to fix this is to change the line to:

encodedData := make([]byte, base64.StdEncoding.EncodedLen(len(data)))

. Base64 , , base64.StdEncoding.EncodedLen().

. :

. NewEncoder().

NewEncoder() :

func main() {
    data := []byte("string of data")

    encodedData := &bytes.Buffer{}
    encoder := base64.NewEncoder(base64.StdEncoding, encodedData)
    defer encoder.Close()
    encoder.Write(data)

    fmt.Println(encodedData)
}

, EncodeToString(), : encodedData := base64.StdEncoding.EncodeToString(data).

+4

. ,

package main

import (
    "encoding/base64"
    "fmt"
)

func main() {
    data := []byte("string of data")
    encodedData := make([]byte, base64.StdEncoding.EncodedLen(len(data)))
    base64.StdEncoding.Encode(encodedData, data)
    fmt.Println(encodedData)
}

:

[99 51 82 121 97 87 53 110 73 71 57 109 73 71 82 104 100 71 69 61]

var encodedData []byte - . index out of range

+4

Encode , dst .

src, enc, EncodedLen (len (src)) dst.

+1

Source: https://habr.com/ru/post/1676320/


All Articles