Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Illegal base64 data at input byte 4 when using base64.StdEncoding.DecodeString(str)

Tags:

base64

go

I am getting: error: illegal base64 data at input byte 4

When passing in Base64Image into base64.StdEncoding.DecodeString(str):

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA... 

Let me know if you need the full base64, I have just pasted in the first part as it looks like the problem is within 4 byte?

data, errBase := base64.StdEncoding.DecodeString(Base64Image)
if errBase != nil {
    fmt.Println("error:", errBase)
    return false
}

Do you know why?

like image 496
Chris G. Avatar asked Jun 24 '15 16:06

Chris G.


4 Answers

Also this may happen if you encoded using StdEncoding and trying to decode using RawStdEncoding

like image 169
Grzegorz Barański Avatar answered Oct 30 '22 16:10

Grzegorz Barański


Not all of your input string you try to decode is Base64 encoded form.

What you have is a Data URI scheme, that provides a way to include data in-line in web pages as if they were external resources.

It has a format of:

data:[<MIME-type>][;charset=<encoding>][;base64],<data>

Where in your case image/png is the MIME-type, the optional charset is missing, and ";base64" is a constant string indicating that <data> is encoded using Base64 encoding.

To acquire the data (that is the Base64 encoded form), cut off the prefix up to the comma (comma included):

input := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA"

b64data := input[strings.IndexByte(input, ',')+1:]
fmt.Println(b64data)

Output:

iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA

Of which you can now decode:

data, err := base64.StdEncoding.DecodeString(b64data)
if err != nil {
    fmt.Println("error:", err)
}
fmt.Println(data)

Output:

[137 80 78 71 13 10 26 10 0 0 0 13 73 72 68 82 0 0 0 100 0 0 0 100 8 6 0]

Try it on the Go Playground.

like image 31
icza Avatar answered Oct 30 '22 17:10

icza


Sometimes this happens if your base64 string is not properly padded with == at the end.

like image 3
Erkin Djindjiev Avatar answered Oct 30 '22 17:10

Erkin Djindjiev


It's because your string isn't in base64 until after the comma data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA...

import "strings" and use split to get the half after the comma and then call decodestring with that.

import "strings"

data, errBase := base64.StdEncoding.DecodeString(strings.Split(Base64Image, "base64,")[1]))
if errBase != nil {
    fmt.Println("error:", errBase)
    return false
}

EDIT: made the split token base64, because it's more specific to your input.

like image 2
evanmcdonnal Avatar answered Oct 30 '22 16:10

evanmcdonnal