Encode Unpadded URL Tokens With RawURLEncoding

Encode binary tokens cleanly with base64.RawURLEncoding and hex.EncodeToString, showing how unpadded decoders reject trailing equals signs.

GoAuth Jwt

Code

gosnippet
28 lines
package main

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

func main() {
	raw := []byte{0xde, 0xad, 0xbe, 0xef, 0xfb, 0xff, 0x10}

	// RawURLEncoding drops '=' padding and swaps '+/' for '-_'
	token := base64.RawURLEncoding.EncodeToString(raw)
	fingerprint := hex.EncodeToString(raw[:4])
	fmt.Printf("token=%s (len=%d)\n", token, len(token))
	fmt.Printf("hex prefix=%s\n", fingerprint)

	decoded, err := base64.RawURLEncoding.DecodeString(token)
	if err != nil {
		fmt.Println("decode failed:", err)
		return
	}
	fmt.Printf("roundtrip match=%t\n", string(decoded) == string(raw))

	// Raw encodings strictly reject trailing '=' padding
	_, padErr := base64.RawURLEncoding.DecodeString(token + "=")
	fmt.Printf("padded input rejected=%t\n", padErr != nil)
}

Runtime walkthrough — Encode Unpadded URL Tokens With RawURLEncoding

Everything happens inside the function main.

Error handling is inline: 1 place test err != nil and branch immediately.

What to watch for

  • Runs on the standard library alone; nothing to install.

Using it

Look first at the signature func main()

Stdout emits prefixed indicators — token=, hex prefix=, decode failed: — when the file runs.

Key statements

if err != nil {
	fmt.Println("decode failed:", err)
	return
}

Interactive Tools for This Topic

FAQ

What does Encode Unpadded URL Tokens With RawURLEncoding print when run?
Execute the whole file; each printed line is prefixed with a label like `token=`, `hex prefix=`, `decode failed:`.