douzao5487 2018-10-30 14:32
浏览 627
已采纳

Base64编码不会因无效字符而失败[关闭]

I am trying to ensure a string coming from an http request is valid for use in a base64 url param. I've been experimenting with base64.RawURLEncoding as I assumed encoding an invalid string would throw an err, or at least decoding the result of this would fail, however it quite happily encodes/decodes the string regardless of the input.

https://play.golang.org/p/3sHUfl2NSJK

I have created the above playground showing the issue I'm having (albeit an extreme example). Is there another way of ascertaining whether a string consists entirely of valid base64 characters?

  • 写回答

2条回答 默认 最新

  • dqssst0144 2018-10-30 15:03
    关注

    To clarify, Base64 is an encoding scheme which allows you to take arbitrary binary data and safely encode it into ASCII characters which can later be decoded into the original binary string.

    That means that the "Base64-encode" operation can take literally any input and produce valid, encoded data. However, the "Base64-decode" operation will fail if its input string contains characters outside of set of ASCII characters that the encoding uses (meaning that the given string was not produced by a valid Base64-encoder).

    To test if a string contains a valid Base64 encoded sequence, you just need to call base64.Encoding.DecodeString(...) and test if the error is "nil".

    For example (Go Playground):

    func IsValidBase64(s string) bool {
      _, err := base64.StdEncoding.DecodeString(s)
      return err == nil
    }
    
    func main() {
      ss := []string{"ABBA", "T0sh", "Foo=", "Bogus\x01"}
    
      for _, s := range ss {
        if IsValidBase64(s) {
          fmt.Printf("OK: valid Base64 %q
    ", s)
        } else {
          fmt.Printf("ERR: invalid Base64 %q
    ", s)
        }
      }
      // OK: valid Base64 "ABBA"
      // OK: valid Base64 "T0sh"
      // OK: valid Base64 "Foo="
      // ERR: invalid Base64 "Bogus\x01"
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3