Base32 Encoding For Shared Secrets
Encode and decode Base32 with padded, unpadded, and custom alphabets for OTP secrets and case-insensitive configuration values.
Code
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
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.