使用 libcurl + OpenSSL 实现完整验证流程
以下代码演示了如何使用 libcurl 发送 HTTP 请求,并通过 OpenSSL 计算 MD5 签名,最后验证服务器返回的签名和时间戳。
// 卡密验证 C++ 示例(libcurl + OpenSSL) #include <curl/curl.h> #include <openssl/md5.h> #include <sstream> #include <ctime> // 回调函数:将响应数据写入 string size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* output) { size_t total = size * nmemb; output->append((char*)contents, total); return total; } // MD5 计算函数 std::string md5(const std::string& data) { unsigned char hash[MD5_DIGEST_LENGTH]; MD5((unsigned char*)data.c_str(), data.size(), hash); char buf[33] = {0}; for (int i = 0; i < 16; i++) sprintf(buf + i * 2, "%02x", hash[i]); return std::string(buf); } // 验证服务器响应(签名 + 时间戳防重放) bool verifyResponse(const std::string& raw, const std::string& signKey, std::string& biz) { // 提取签名 size_t pos = raw.find("|sign="); if (pos == std::string::npos) return false; std::string body = raw.substr(0, pos); std::string sign = raw.substr(pos + 6); // 本地计算签名并比对 std::string localSign = md5(body + signKey); if (localSign != sign) return false; // 提取时间戳并校验(120秒内有效) size_t lastPipe = body.rfind('|'); if (lastPipe == std::string::npos) return false; std::string tsStr = body.substr(lastPipe + 1); long ts = atol(tsStr.c_str()); long nowTs = time(nullptr); if (abs(nowTs - ts) > 120) return false; biz = body.substr(0, lastPipe); // 业务数据 return true; }
signKey(后台分配)一同计算 MD5。|sign=xxx,比对本地计算的签名,同时校验时间戳(防重放)。 提示: 实际使用时,请将 signKey 和接口地址替换为后台分配的真实值。完整请求示例可参考 文档首页 中的通用对接流程。