Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created July 6, 2018 18:21
Show Gist options
  • Save xeoncross/e83313ac7157c659416676a6044fcd1e to your computer and use it in GitHub Desktop.
Save xeoncross/e83313ac7157c659416676a6044fcd1e to your computer and use it in GitHub Desktop.
Base 64 encode and decode a byte array in Golang. https://play.golang.org/p/X4z9zq0nXlW
package main
import (
"fmt"
"encoding/base64"
)
func main() {
str := "Hello, playground :)"
b := Base64Encode([]byte(str))
fmt.Printf("%q\n", b)
msg, err := Base64Decode(b)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%q\n", msg)
}
func Base64Encode(message []byte) []byte {
b := make([]byte, base64.StdEncoding.EncodedLen(len(message)))
base64.StdEncoding.Encode(b, message)
return b
}
func Base64Decode(message []byte) (b []byte, err error) {
var l int
b = make([]byte, base64.StdEncoding.DecodedLen(len(message)))
l, err = base64.StdEncoding.Decode(b, message)
if err != nil {
return
}
return b[:l], nil
}
@xeoncross
Copy link
Author

Decoding is a non-obvious task since you must estimate the size of the resulting byte slice and trim off any remaining \x00 null bytes.

@xeoncross
Copy link
Author

xeoncross commented Jul 6, 2018

If working with strings, this is already handled for you in the stdlib:

https://golang.org/pkg/encoding/base64/#Encoding.DecodeString

func Base64Encode(src []byte) []byte {
    return []byte(base64.StdEncoding.EncodeToString(src))
}

func Base64Decode(src []byte) ([]byte, error) {
    return base64.StdEncoding.DecodeString(string(src))
}

@mweibel
Copy link

mweibel commented Nov 13, 2020

thanks 👍

Maybe this would make sense as an example in the official docs? (the byte decoding)

@mathisve
Copy link

mathisve commented Feb 3, 2021

Saved my day! Thanks

@Jawadh-Salih
Copy link

I am trying to Decode a base64 encoded byte array. But when I convert it to a string variable and pass it to DecodeString() function, then it always gives me the CorruptInputError. But when I get the string value and pass it into the DecodeString() function, then it does the decoding smoothly.

Any help is much appreciated...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment