// ServerBike Reseller Public API: BRIDGE-HMAC-SHA256-V1 signer (Go 1.20+, standard library only). // Usage: go run serverbike_sign.go ../vectors.json package main import ( "crypto/hmac" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "os" "regexp" "strconv" "strings" "time" ) var wireRe = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`) // DecodeSecret turns the issued 43-character unpadded base64url secret into its 32 key bytes. func DecodeSecret(wire string) ([]byte, error) { if !wireRe.MatchString(wire) { return nil, errors.New("secret must be 43 unpadded base64url characters") } raw, err := base64.RawURLEncoding.DecodeString(wire) if err != nil || len(raw) != 32 || base64.RawURLEncoding.EncodeToString(raw) != wire { return nil, errors.New("non-canonical secret") } return raw, nil } // CanonicalMessage builds the exact bytes that are signed (LF-separated, no trailing LF). func CanonicalMessage(timestamp, nonce, method, rawTarget string, body []byte) string { path, query := rawTarget, "-" if i := strings.IndexByte(rawTarget, '?'); i >= 0 { path, query = rawTarget[:i], "?"+rawTarget[i+1:] } sum := sha256.Sum256(body) return strings.Join([]string{"BRIDGE-HMAC-SHA256-V1", "reseller-public", timestamp, nonce, method, path, query, hex.EncodeToString(sum[:])}, "\n") } // Sign returns the four request headers. Pass empty timestamp/nonce for fresh values. func Sign(secret []byte, credentialID, method, rawTarget string, body []byte, timestamp, nonce string) map[string]string { if timestamp == "" { timestamp = strconv.FormatInt(time.Now().Unix(), 10) } if nonce == "" { b := make([]byte, 16) _, _ = rand.Read(b) nonce = base64.RawURLEncoding.EncodeToString(b) } m := hmac.New(sha256.New, secret) m.Write([]byte(CanonicalMessage(timestamp, nonce, method, rawTarget, body))) return map[string]string{"X-Reseller-Credential-Id": credentialID, "X-Request-Timestamp": timestamp, "X-Request-Nonce": nonce, "X-Request-Signature": "v1=" + hex.EncodeToString(m.Sum(nil))} } func main() { if len(os.Args) != 2 { fmt.Fprintln(os.Stderr, "usage: go run serverbike_sign.go ") os.Exit(2) } data, err := os.ReadFile(os.Args[1]) if err != nil { panic(err) } var vs []map[string]string if err := json.Unmarshal(data, &vs); err != nil { panic(err) } for _, v := range vs { secret, err := DecodeSecret(v["secret_wire"]) if err != nil { panic(err) } h := Sign(secret, v["credential_id"], v["method"], v["target"], []byte(v["body"]), v["timestamp"], v["nonce"]) if h["X-Request-Signature"] != v["signature"] || CanonicalMessage(v["timestamp"], v["nonce"], v["method"], v["target"], []byte(v["body"])) != v["canonical_message"] { fmt.Fprintln(os.Stderr, "MISMATCH", v["method"], v["target"]) os.Exit(1) } } fmt.Printf("go: %d vectors OK\n", len(vs)) }