Skip to content

Instantly share code, notes, and snippets.

@xrl
Created August 24, 2015 22:36
Show Gist options
  • Save xrl/c67382011efa2180428c to your computer and use it in GitHub Desktop.
Save xrl/c67382011efa2180428c to your computer and use it in GitHub Desktop.
Go example code for flexible decoding of unpadded URL encoded base64 and std encoding
package main
import "fmt"
import "encoding/base64"
import "bytes"
var suspiciousBase64 = []byte(`OSEeu8fWTcq+AliFG3PlZ0eYR8zFWWAdkCwb3XbPE96wvAsiF1W6v2Udg5KoDe7M2d0oQMmpoNeC
ZQWRMBHarz5vHzfTSXXCjvoLfZJVA1FLiJ9RYk8ulFyEJF19nxd2GLArnWjiqsP9RslhFB3BvYnZ
O9IsuyRqWKpa1nl5B68=`)
func main() {
decoded,err := decodeUnpaddedBase64(suspiciousBase64, false)
if err != nil {
fmt.Printf("could not process value: `%s`", err)
} else {
fmt.Printf("it worked! %d", len(decoded))
}
}
var padding = []byte("=")
func decodeUnpaddedBase64(incoming []byte, isURLEncoded bool) (decoded []byte, err error) {
decoded = make([]byte, len(incoming))
if isURLEncoded {
if m := len(incoming) % 4; m != 0 {
paddingBytes := bytes.Repeat(padding, 4-m)
incoming = append(incoming, paddingBytes[:]...)
}
_,err = base64.URLEncoding.Decode(decoded, incoming)
} else {
_,err = base64.StdEncoding.Decode(decoded, incoming)
}
if(err != nil){
return
}
return
}
@xrl
Copy link
Author

xrl commented Aug 24, 2015

I thought this code would be handy for folks who are getting errors about: illegal base64 data at input byte 2, etc.

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