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
}
@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