技术文档

C++ 对接卡密验证

使用 libcurl + OpenSSL 实现完整验证流程

本文档提供 C++ 语言调用卡密验证接口的完整示例,包含签名计算、时间戳防重放、响应校验等核心逻辑。

完整实现代码

以下代码演示了如何使用 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;
}

关键步骤说明

  • 1. 发送请求:使用 libcurl 向卡密验证接口 POST 数据(卡密、机器码等)。
  • 2. 签名计算:将业务数据(不含签名)拼接后,与 signKey(后台分配)一同计算 MD5。
  • 3. 响应校验:提取返回字符串中的 |sign=xxx,比对本地计算的签名,同时校验时间戳(防重放)。
  • 4. 获取业务数据:验证通过后,从响应中提取有效信息(如授权状态、剩余天数等)。

提示: 实际使用时,请将 signKey 和接口地址替换为后台分配的真实值。完整请求示例可参考 文档首页 中的通用对接流程。