Base64 Decode not complete

Issue

I have bee trying to decode some string returned from other system, but the decoded string have different result if i decode with online decoder or using PHP. I’ve been trying using base64.StdEncoding.DecodeString() and base64.StdEncoding.Decode() but the result still not the same as the result of online decoder or PHP code.

Here is my code:

// encoded string
s := "HxJVICMcHCYeHUJcEWISWk09JgxHBwRPXHlHWFoGf1JXCkgFS1xXVU9Ze1FSCUwUIFMdGx0-SglVDmRNUHdAJRETRR0hHx0aIB1OExcgUCkeRyEaDUE5Y1oTREhcCRJSXAtWHBwfJSUYFUALUFd-VlkIU0JYFg5TA04PURA_OFBQXHpXWVxTSEZlC1FZTH4TKTUXGx1ORBcfSB0fO0xRJRoRVxsmExcoIhxEAxsQfF9bD1tXSQd-XEkBShEoPH80UWEJWAhAQhA0XgNVTwdWZxEX"

// add '=' on the right string
strHelper := string2.NewStringHelper()
sl := math.Ceil(float64(len(s) / 4 * 4))
sp := strHelper.StrPadRight(s, "=", int(sl))
sp = strtr(sp, map[string]string{"-_": "+/"})
  
// decode the string using base64.StdEncoding.DecodeString()
spb, _ := base64.StdEncoding.DecodeString(sp)
  
// decode the string using base64.StdEncoding.Decode()
b64 := make([]byte, base64.StdEncoding.DecodedLen(len(sp)))
n, err := base64.StdEncoding.Decode(b64, []byte(sp))

// decode the string using base64.NewDecoder()
b64s := strings.NewReader(sp)
b64d := base64.NewDecoder(base64.StdEncoding, b64s)
buf := new(strings.Builder)
io.Copy(buf, b64d)

// result of decoded string
U #&B\bZM=&GO\yGXZRW
HK\WUOY{QR L S

// result from online decoder or PHP
U #&B\bZM=&GO\yGXZRW
HK\WUOY{QR L S>J   UdMPw@%E! N P)G!
A9cZDH\    R\V%%@PW~VYSBXSNQ?8PP\zWY\SHFeQYL~)5NDH;LQ%W&("D|_[[WI~\IJ(<4Qa    X@B4^UOVg

https://go.dev/play/p/Yqf2I2QgWxS

Please can someone enlightened me where my code is wrong?

Solution

Never omit errors in Go! If you check it:

data, err := base64.StdEncoding.DecodeString(s)
if err != nil {
    panic(err)
}

Output:

panic: illegal base64 data at input byte 71

Your input is constructed not from the standard Base64 charset. The standard charset uses the + and / characters. Your input is constructed using a modified charset, a charset safe and used to transmit encoded values in URLs which uses - and _.

So decode using base64.URLEncoding:

data, err := base64.URLEncoding.DecodeString(s)
if err != nil {
    panic(err)
}

fmt.Println(string(data))

This will not result in an error (try it on the Go Playground).

If your input does not contain the padding characters, then use base64.RawURLEncoding.

Answered By – icza

Answer Checked By – Mary Flores (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.