forlayo
forlayo

Reputation: 1688

Base64 encode/decode without padding on golang ( appengine )

There's a way to encode/decode a string to/from Base64 without having the padding at the end? I mean the '==' ending.

I'm using base64.URLEncoding.EncodeToString to encode and it works perfectly but I didn't see a way to decide to not use the padding at the end ( like on java ).

Upvotes: 11

Views: 16466

Answers (4)

David Thomas
David Thomas

Reputation: 4396

To omit padding characters for base64 encoding in golang and make the result url safe, you can use

value := base64.RawURLEncoding.EncodeToString(bytes)

RawURLEncoding is the unpadded alternate base64 encoding defined in RFC 4648. It is typically used in URLs and file names. This is the same as URLEncoding but omits padding characters.

https://pkg.go.dev/encoding/base64

Upvotes: 0

Caffeines
Caffeines

Reputation: 207

To Encode:

str := "encode this"
encodedStr := base64.StdEncoding.
    WithPadding(base64.NoPadding).
    EncodeToString([]byte(str))

fmt.Println(encodedStr)

To Decode:

data, err := base64.
    StdEncoding.WithPadding(base64.NoPadding).
    DecodeString(encodedStr)

if err != nil {
    fmt.Println(err)
}

fmt.Println(string(data))

Go Playground: https://go.dev/play/p/TAZgLMSSe-K

Upvotes: 1

Somo  S.
Somo S.

Reputation: 4185

Simply,

use base64.RawStdEncoding.EncodeToString instead of base64.StdEncoding.EncodeToString

OR else

use base64.RawURLEncoding.EncodeToString instead of base64.URLEncoding.EncodeToString.

Reference: see source-code comments Line 94 to 110:

// RawURLEncoding is the unpadded alternate base64 encoding defined in RFC 4648.
// It is typically used in URLs and file names.
// This is the same as URLEncoding but omits padding characters.

Upvotes: 9

Mr_Pink
Mr_Pink

Reputation: 109432

Go1.5 will have a WithPadding option on Encoding.

This also will add 2 pre-defined encodings, RawStdEncoding, and RawURLEncoding, which will have no padding.

Though since you're on app-engine, and won't have access to Go1.5 for a while, you can make some helper function to add and remove the padding as needed.

Here is an example to encode and decode strings. If you need, it could easily be adapted to work more efficiently using []byte.

func base64EncodeStripped(s string) string {
    encoded := base64.StdEncoding.EncodeToString([]byte(s))
    return strings.TrimRight(encoded, "=")
}

func base64DecodeStripped(s string) (string, error) {
    if i := len(s) % 4; i != 0 {
        s += strings.Repeat("=", 4-i)
    }
    decoded, err := base64.StdEncoding.DecodeString(s)
    return string(decoded), err
}

Upvotes: 21

Related Questions