package wecom import ( "crypto/aes" "crypto/cipher" "crypto/sha1" "encoding/base64" "encoding/binary" "fmt" "sort" "strings" ) // CallbackConfig holds the parameters needed for WeCom callback URL verification. // These are generated by the WeCom admin console when configuring "接收消息服务器URL". type CallbackConfig struct { Token string `json:"callback_token"` EncodingAESKey string `json:"callback_aes_key"` CorpID string `json:"corp_id"` } // VerifyCallback verifies a WeCom callback URL verification request and returns // the decrypted echostr that should be sent back as the HTTP response body. // // WeCom sends a GET request with query params: msg_signature, timestamp, nonce, echostr. // We must verify the signature, decrypt echostr, and return the plaintext. func VerifyCallback(cfg CallbackConfig, msgSignature, timestamp, nonce, echostr string) ([]byte, error) { if cfg.Token == "" || cfg.EncodingAESKey == "" || cfg.CorpID == "" { return nil, fmt.Errorf("incomplete callback config: token, encoding_aes_key, and corp_id are all required") } // Step 1: Verify signature = SHA1(sort(token, timestamp, nonce, echostr)) if err := verifySignature(cfg.Token, timestamp, nonce, echostr, msgSignature); err != nil { return nil, fmt.Errorf("signature verification failed: %w", err) } // Step 2: Decode the AES key (EncodingAESKey is 43-char base64 without trailing '=') aesKey, err := base64.StdEncoding.DecodeString(cfg.EncodingAESKey + "=") if err != nil { return nil, fmt.Errorf("decode EncodingAESKey: %w", err) } if len(aesKey) != 32 { return nil, fmt.Errorf("invalid AES key length: got %d, want 32", len(aesKey)) } // Step 3: Base64-decode the echostr ciphertext ciphertext, err := base64.StdEncoding.DecodeString(echostr) if err != nil { return nil, fmt.Errorf("base64 decode echostr: %w", err) } // Step 4: AES-256-CBC decrypt (IV = first 16 bytes of AES key) plaintext, err := aesDecrypt(ciphertext, aesKey) if err != nil { return nil, fmt.Errorf("AES decrypt: %w", err) } // Step 5: Parse plaintext: 16-byte random + 4-byte msg_len (big-endian) + msg + corp_id if len(plaintext) < 20 { return nil, fmt.Errorf("decrypted data too short: %d bytes", len(plaintext)) } msgLen := binary.BigEndian.Uint32(plaintext[16:20]) if 20+int(msgLen) > len(plaintext) { return nil, fmt.Errorf("invalid msg_len %d, plaintext only %d bytes", msgLen, len(plaintext)) } msg := plaintext[20 : 20+msgLen] receivedCorpID := string(plaintext[20+msgLen:]) if receivedCorpID != cfg.CorpID { return nil, fmt.Errorf("corp_id mismatch: expected %q, got %q", cfg.CorpID, receivedCorpID) } return msg, nil } func verifySignature(token, timestamp, nonce, echostr, expected string) error { parts := []string{token, timestamp, nonce, echostr} sort.Strings(parts) h := sha1.New() h.Write([]byte(strings.Join(parts, ""))) got := fmt.Sprintf("%x", h.Sum(nil)) if got != expected { return fmt.Errorf("got %s, expected %s", got, expected) } return nil } func aesDecrypt(ciphertext, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } if len(ciphertext)%aes.BlockSize != 0 { return nil, fmt.Errorf("ciphertext length %d is not a multiple of block size %d", len(ciphertext), aes.BlockSize) } iv := key[:aes.BlockSize] mode := cipher.NewCBCDecrypter(block, iv) plaintext := make([]byte, len(ciphertext)) mode.CryptBlocks(plaintext, ciphertext) // PKCS#7 unpadding if len(plaintext) == 0 { return nil, fmt.Errorf("empty plaintext after decryption") } padLen := int(plaintext[len(plaintext)-1]) if padLen < 1 || padLen > aes.BlockSize || padLen > len(plaintext) { return nil, fmt.Errorf("invalid PKCS7 padding: %d", padLen) } return plaintext[:len(plaintext)-padLen], nil }