Base32 Encoding For Shared Secrets

Encode and decode Base32 with padded, unpadded, and custom alphabets for OTP secrets and case-insensitive configuration values.

GoAuth Jwt

Code

snippet
package main

import (
	"encoding/base32"
	"fmt"
	"strings"
)

func main() {
	secret := []byte("otp-secret-2026")

	// StdEncoding 带 = 填充,适合配置文件与密钥文本
	encoded := base32.StdEncoding.EncodeToString(secret)
	fmt.Println("encoded:", encoded)
	fmt.Println("length:", len(encoded))

	// 解码接受小写字母,但不接受字母表之外的字符
	decoded, err := base32.StdEncoding.DecodeString(strings.ToLower(encoded))
	if err != nil {
		fmt.Println("decode failed:", err)
		return
	}
	fmt.Println("roundtrip:", string(decoded) == string(secret))

	// NoPadding:去掉尾部 =,常见于一次性密码与 URL 场景
	raw := base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(secret)
	fmt.Println("no padding:", raw, "| has equals:", strings.HasSuffix(raw, "="))

	// 自定义 32 字符字母表:Crockford 风格去掉易混淆字符
	custom := base32.NewEncoding("0123456789ABCDEFGHJKMNPQRSTVWXYZ").WithPadding(base32.NoPadding)
	fmt.Println("custom:", custom.EncodeToString(secret))
}

The way it runs

Base32 Encoding For Shared Secrets is built around the function main.

Nothing falls through silently — 1 checkpoint test err != nil on the way through.

Points of care

  • The import surface (if any) is all standard library, all versioned with the language itself.

Using it

Output lines are prefixed (encoded:, length:, decode failed:), so the effect of each step announces itself.

Key statements

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

Interactive Tools for This Topic

FAQ

What does Base32 Encoding For Shared Secrets print when run?
Invoke the file as-is — the `encoded:`, `length:`, `decode failed:` prefixes identify which step printed each line.