编码/解码 base64

huangapple go评论120阅读模式
英文:

Encode/Decode base64

问题

这是我的代码,我不明白为什么解码函数不起作用。

请给予一些见解,谢谢。

  1. func EncodeB64(message string) (retour string) {
  2. base64Text := make([]byte, base64.StdEncoding.EncodedLen(len(message)))
  3. base64.StdEncoding.Encode(base64Text, []byte(message))
  4. return string(base64Text)
  5. }
  6. func DecodeB64(message string) (retour string) {
  7. base64Text := make([]byte, base64.StdEncoding.DecodedLen(len(message)))
  8. base64.StdEncoding.Decode(base64Text, []byte(message))
  9. fmt.Printf("base64: %s\n", base64Text)
  10. return string(base64Text)
  11. }

它给了我以下输出:
[解码错误 - 输出不是utf-8][解码错误 - 输出不是utf-8]

英文:

here is my code and I don't understand why the decode function doesn't work.

Little insight would be great please.

  1. func EncodeB64(message string) (retour string) {
  2. base64Text := make([]byte, base64.StdEncoding.EncodedLen(len(message)))
  3. base64.StdEncoding.Encode(base64Text, []byte(message))
  4. return string(base64Text)
  5. }
  6. func DecodeB64(message string) (retour string) {
  7. base64Text := make([]byte, base64.StdEncoding.DecodedLen(len(message)))
  8. base64.StdEncoding.Decode(base64Text, []byte(message))
  9. fmt.Printf("base64: %s\n", base64Text)
  10. return string(base64Text)
  11. }

It gaves me :
[Decode error - output not utf-8][Decode error - output not utf-8]

答案1

得分: 58

The len prefix is superficial and causes the invalid utf-8 error:

  1. package main
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "log"
  6. )
  7. func main() {
  8. str := base64.StdEncoding.EncodeToString([]byte("Hello, playground"))
  9. fmt.Println(str)
  10. data, err := base64.StdEncoding.DecodeString(str)
  11. if err != nil {
  12. log.Fatal("error:", err)
  13. }
  14. fmt.Printf("%q\n", data)
  15. }

(Also here)


Output

  1. SGVsbG8sIHBsYXlncm91bmQ=
  2. "Hello, playground"

EDIT: I read too fast, the len was not used as a prefix. dystroy got it right.

英文:

The len prefix is superficial and causes the invalid utf-8 error:

  1. package main
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "log"
  6. )
  7. func main() {
  8. str := base64.StdEncoding.EncodeToString([]byte("Hello, playground"))
  9. fmt.Println(str)
  10. data, err := base64.StdEncoding.DecodeString(str)
  11. if err != nil {
  12. log.Fatal("error:", err)
  13. }
  14. fmt.Printf("%q\n", data)
  15. }

(Also here)


Output

  1. SGVsbG8sIHBsYXlncm91bmQ=
  2. "Hello, playground"

EDIT: I read too fast, the len was not used as a prefix. dystroy got it right.

答案2

得分: 34

DecodedLen 返回的是最大长度。

这个长度对于调整缓冲区的大小很有用,但是缓冲区的一部分不会被写入,因此不会是有效的 UTF-8。

你必须只使用 Decode 函数返回的实际写入长度。

  1. l, _ := base64.StdEncoding.Decode(base64Text, []byte(message))
  2. log.Printf("base64: %s\n", base64Text[:l])
英文:

DecodedLen returns the maximal length.

This length is useful for sizing your buffer but part of the buffer won't be written and thus won't be valid UTF-8.

You have to use only the real written length returned by the Decode function.

  1. l, _ := base64.StdEncoding.Decode(base64Text, []byte(message))
  2. log.Printf("base64: %s\n", base64Text[:l])

答案3

得分: 27

func base64Encode(str string) string {
return base64.StdEncoding.EncodeToString([]byte(str))
}

func base64Decode(str string) (string, bool) {
data, err := base64.StdEncoding.DecodeString(str)
if err != nil {
return "", true
}
return string(data), false
}

英文:

To sum up the other two posts, here are two simple functions to encode/decode Base64 strings with Go:

  1. // Dont forget to import "encoding/base64"!
  2. func base64Encode(str string) string {
  3. return base64.StdEncoding.EncodeToString([]byte(str))
  4. }
  5. func base64Decode(str string) (string, bool) {
  6. data, err := base64.StdEncoding.DecodeString(str)
  7. if err != nil {
  8. return "", true
  9. }
  10. return string(data), false
  11. }

Try it!

答案4

得分: 3

@Denys Séguret的答案几乎100%正确。为了避免在base64Text中浪费未使用的空间,你应该使用base64.DecodedLen。看一下base64.DecodeString如何使用它。
代码应该是这样的:

  1. func main() {
  2. message := base64.StdEncoding.EncodeToString([]byte("Hello, playground"))
  3. base64Text := make([]byte, base64.StdEncoding.DecodedLen(len(message)))
  4. n, _ := base64.StdEncoding.Decode(base64Text, []byte(message))
  5. fmt.Println("base64Text:", string(base64Text[:n]))
  6. }

这里尝试一下。

英文:

@Denys Séguret's answer is almost 100% correct. As an improvement to avoid wasting memory with non used space in base64Text, you should use base64.DecodedLen. Take a look at how base64.DecodeString uses it.
It should look like this:

  1. func main() {
  2. message := base64.StdEncoding.EncodeToString([]byte("Hello, playground"))
  3. base64Text := make([]byte, base64.StdEncoding.DecodedLen(len(message)))
  4. n, _ := base64.StdEncoding.Decode(base64Text, []byte(message))
  5. fmt.Println("base64Text:", string(base64Text[:n]))
  6. }

Try it here.

答案5

得分: 3

func (s secure) encodePayload(body []byte) string {
//Base64编码
return base64.StdEncoding.EncodeToString(body)
}

func (s secure) decodePayload(body []byte) ([]byte, error) {
//Base64解码
b64 := make([]byte, base64.StdEncoding.DecodedLen(len(body)))
n, err := base64.StdEncoding.Decode(b64, body)
if err != nil {
return nil, err
}
return b64[:n], nil
}

英文:

More or less like above, but using []bytes and part of a bigger struct:

  1. func (s secure) encodePayload(body []byte) string {
  2. //Base64 Encode
  3. return base64.StdEncoding.EncodeToString(body)
  4. }
  5. func (s secure) decodePayload(body []byte) ([]byte, error) {
  6. //Base64 Decode
  7. b64 := make([]byte, base64.StdEncoding.DecodedLen(len(body)))
  8. n, err := base64.StdEncoding.Decode(b64, body)
  9. if err != nil {
  10. return nil, err
  11. }
  12. return b64[:n], nil
  13. }

huangapple
  • 本文由 发表于 2013年3月11日 16:39:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/15334220.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定