4
0

base64.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. package codec
  2. import (
  3. "encoding/base64"
  4. )
  5. // likelyBase64Chars is a set of characters that you would expect to find at
  6. // least one of in base64 encoded data. This risks missing about 1% of
  7. // base64 encoded data that doesn't contain these characters, but gives you
  8. // the performance gain of not trying to decode a lot of long symbols in code.
  9. var likelyBase64Chars = make([]bool, 256)
  10. func init() {
  11. for _, c := range `0123456789+/-_` {
  12. likelyBase64Chars[c] = true
  13. }
  14. }
  15. // decodeBase64 decodes base64 encoded printable ASCII characters
  16. func decodeBase64(encodedValue string) string {
  17. // Exit early if it doesn't seem like base64
  18. if !hasByte(encodedValue, likelyBase64Chars) {
  19. return ""
  20. }
  21. // Try standard base64 decoding
  22. decodedValue, err := base64.StdEncoding.DecodeString(encodedValue)
  23. if err == nil && isPrintableASCII(decodedValue) {
  24. return string(decodedValue)
  25. }
  26. // Try base64url decoding
  27. decodedValue, err = base64.RawURLEncoding.DecodeString(encodedValue)
  28. if err == nil && isPrintableASCII(decodedValue) {
  29. return string(decodedValue)
  30. }
  31. return ""
  32. }