base64url.go 715 B

123456789101112131415161718192021222324252627282930313233
  1. // base64url provides base64url encoding/decoding functions
  2. package base64
  3. import (
  4. "encoding/base64"
  5. "strings"
  6. )
  7. // decodes base64url string to bytes
  8. func DecodeURL(data string) ([]byte, error) {
  9. data = strings.Replace(data, "-", "+", -1)
  10. data = strings.Replace(data, "_", "/", -1)
  11. switch len(data) % 4 {
  12. case 0:
  13. case 2:
  14. data += "=="
  15. case 3:
  16. data += "="
  17. }
  18. return base64.StdEncoding.DecodeString(data)
  19. }
  20. // encodes given bytes to base64url string
  21. func EncodeURL(data []byte) string {
  22. result := base64.StdEncoding.EncodeToString(data)
  23. result = strings.Replace(result, "+", "-", -1)
  24. result = strings.Replace(result, "/", "_", -1)
  25. result = strings.Replace(result, "=", "", -1)
  26. return result
  27. }