Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode/Decode base64

Tags:

base64

go

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

Little insight would be great please.

func EncodeB64(message string) (retour string) {
    base64Text := make([]byte, base64.StdEncoding.EncodedLen(len(message)))
    base64.StdEncoding.Encode(base64Text, []byte(message))
    return string(base64Text)
}

func DecodeB64(message string) (retour string) {
    base64Text := make([]byte, base64.StdEncoding.DecodedLen(len(message)))
    base64.StdEncoding.Decode(base64Text, []byte(message))
    fmt.Printf("base64: %s\n", base64Text)
    return string(base64Text)
}

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

like image 306
Bussiere Avatar asked Mar 11 '13 08:03

Bussiere


3 Answers

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

package main

import (
        "encoding/base64"
        "fmt"
        "log"
)

func main() {
        str := base64.StdEncoding.EncodeToString([]byte("Hello, playground"))
        fmt.Println(str)

        data, err := base64.StdEncoding.DecodeString(str)
        if err != nil {
                log.Fatal("error:", err)
        }

        fmt.Printf("%q\n", data)
}

(Also here)


Output

SGVsbG8sIHBsYXlncm91bmQ=
"Hello, playground"

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

like image 177
zzzz Avatar answered Nov 12 '22 02:11

zzzz


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.

l, _ := base64.StdEncoding.Decode(base64Text, []byte(message))
log.Printf("base64: %s\n", base64Text[:l])
like image 33
Denys Séguret Avatar answered Nov 12 '22 00:11

Denys Séguret


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

// Dont forget to import "encoding/base64"!

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
}

Try it!

like image 23
fnkr Avatar answered Nov 12 '22 02:11

fnkr