Files

623 lines
21 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// DogProtect keygen — 用工程自带的 RSA 私钥给序列号签名
//
// 序列号格式(与 runtime/licensing_manager.cc 的校验逻辑一致):
// serial = base64( (00 02 || 非零填充 || 00 || payload) ^ d mod n )
// payload = 若干 chunk,最后是 0xFF + sha1(payload 前缀) 的前 4 字节(倒序)
//
// 用法:
// dogkeygen --project <file.dog|license.xml> [选项] # 从工程/授权文件里取密钥
// dogkeygen --modulus <b64> --private-exp <b64> [选项] # 直接给密钥
// dogkeygen --verify <serial> --project <file> # 用公钥验签并解析字段
//
// 选项:--user <名> --email <邮箱> --exp YYYYMMDD --max-build YYYYMMDD
// --running-time <分钟> --hwid <base64> --user-data <hex> --product-code <base64>
// --out <文件>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cstdint>
#include <string>
#include <vector>
typedef std::vector<uint8_t> Bytes;
// ---------------------------------------------------------------- base64
static const char *B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static std::string b64_encode(const Bytes &in)
{
std::string out;
size_t i;
for (i = 0; i + 2 < in.size(); i += 3) {
uint32_t v = (in[i] << 16) | (in[i + 1] << 8) | in[i + 2];
out += B64[(v >> 18) & 63];
out += B64[(v >> 12) & 63];
out += B64[(v >> 6) & 63];
out += B64[v & 63];
}
if (i + 1 == in.size()) {
uint32_t v = in[i] << 16;
out += B64[(v >> 18) & 63];
out += B64[(v >> 12) & 63];
out += "==";
} else if (i + 2 == in.size()) {
uint32_t v = (in[i] << 16) | (in[i + 1] << 8);
out += B64[(v >> 18) & 63];
out += B64[(v >> 12) & 63];
out += B64[(v >> 6) & 63];
out += '=';
}
return out;
}
static Bytes b64_decode(const std::string &str)
{
int8_t map[256];
memset(map, -1, sizeof(map));
for (int i = 0; i < 64; i++)
map[(uint8_t)B64[i]] = (int8_t)i;
Bytes out;
uint32_t buf = 0;
int bits = 0;
for (size_t i = 0; i < str.size(); i++) {
int8_t v = map[(uint8_t)str[i]];
if (v < 0)
continue;
buf = (buf << 6) | (uint32_t)v;
bits += 6;
if (bits >= 8) {
bits -= 8;
out.push_back((uint8_t)((buf >> bits) & 0xFF));
}
}
return out;
}
// ---------------------------------------------------------------- SHA-1
struct SHA1
{
uint32_t h[5];
Bytes buf;
uint64_t total;
SHA1() { reset(); }
void reset()
{
h[0] = 0x67452301; h[1] = 0xEFCDAB89; h[2] = 0x98BADCFE;
h[3] = 0x10325476; h[4] = 0xC3D2E1F0;
buf.clear();
total = 0;
}
static uint32_t rol(uint32_t v, int n) { return (v << n) | (v >> (32 - n)); }
void block(const uint8_t *p)
{
uint32_t w[80];
for (int i = 0; i < 16; i++)
w[i] = ((uint32_t)p[i * 4] << 24) | ((uint32_t)p[i * 4 + 1] << 16) |
((uint32_t)p[i * 4 + 2] << 8) | (uint32_t)p[i * 4 + 3];
for (int i = 16; i < 80; i++)
w[i] = rol(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4];
for (int i = 0; i < 80; i++) {
uint32_t f, k;
if (i < 20) { f = (b & c) | ((~b) & d); k = 0x5A827999; }
else if (i < 40) { f = b ^ c ^ d; k = 0x6ED9EBA1; }
else if (i < 60) { f = (b & c) | (b & d) | (c & d); k = 0x8F1BBCDC; }
else { f = b ^ c ^ d; k = 0xCA62C1D6; }
uint32_t tmp = rol(a, 5) + f + e + k + w[i];
e = d; d = c; c = rol(b, 30); b = a; a = tmp;
}
h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e;
}
void input(const uint8_t *data, size_t size)
{
total += size;
for (size_t i = 0; i < size; i++) {
buf.push_back(data[i]);
if (buf.size() == 64) {
block(&buf[0]);
buf.clear();
}
}
}
void result(uint8_t out[20])
{
uint64_t bits = total * 8;
uint8_t pad = 0x80;
input(&pad, 1);
uint8_t zero = 0;
while (buf.size() != 56)
input(&zero, 1);
uint8_t len[8];
for (int i = 0; i < 8; i++)
len[i] = (uint8_t)(bits >> (56 - i * 8));
input(len, 8);
for (int i = 0; i < 5; i++) {
out[i * 4 + 0] = (uint8_t)(h[i] >> 24);
out[i * 4 + 1] = (uint8_t)(h[i] >> 16);
out[i * 4 + 2] = (uint8_t)(h[i] >> 8);
out[i * 4 + 3] = (uint8_t)h[i];
}
}
};
// ---------------------------------------------------------------- 大数(只做 modpow 需要的几件事)
struct Big
{
std::vector<uint32_t> d; // 小端
Big() {}
Big(uint32_t v) { if (v) d.push_back(v); }
void trim() { while (!d.empty() && d.back() == 0) d.pop_back(); }
bool zero() const { return d.empty(); }
size_t bits() const
{
if (d.empty())
return 0;
uint32_t top = d.back();
size_t n = (d.size() - 1) * 32;
while (top) { n++; top >>= 1; }
return n;
}
static Big from_bytes_be(const uint8_t *p, size_t size)
{
Big r;
r.d.assign((size + 3) / 4, 0);
for (size_t i = 0; i < size; i++) {
size_t pos = size - 1 - i; // 从最低字节开始
r.d[pos / 4] |= (uint32_t)p[i] << ((pos % 4) * 8);
}
r.trim();
return r;
}
Bytes to_bytes_be(size_t len) const
{
Bytes out(len, 0);
for (size_t i = 0; i < len; i++) {
size_t pos = len - 1 - i;
size_t limb = pos / 4;
uint8_t v = limb < d.size() ? (uint8_t)(d[limb] >> ((pos % 4) * 8)) : 0;
out[i] = v;
}
return out;
}
int cmp(const Big &o) const
{
if (d.size() != o.d.size())
return d.size() < o.d.size() ? -1 : 1;
for (size_t i = d.size(); i-- > 0;) {
if (d[i] != o.d[i])
return d[i] < o.d[i] ? -1 : 1;
}
return 0;
}
Big sub(const Big &o) const // 假定 *this >= o
{
Big r;
r.d.assign(d.size(), 0);
int64_t borrow = 0;
for (size_t i = 0; i < d.size(); i++) {
int64_t cur = (int64_t)d[i] - borrow - (i < o.d.size() ? o.d[i] : 0);
if (cur < 0) { cur += ((int64_t)1 << 32); borrow = 1; }
else borrow = 0;
r.d[i] = (uint32_t)cur;
}
r.trim();
return r;
}
Big shl(size_t n) const
{
if (zero())
return Big();
Big r;
size_t words = n / 32, bits = n % 32;
r.d.assign(d.size() + words + 1, 0);
for (size_t i = 0; i < d.size(); i++) {
uint64_t v = (uint64_t)d[i] << bits;
r.d[i + words] |= (uint32_t)v;
r.d[i + words + 1] |= (uint32_t)(v >> 32);
}
r.trim();
return r;
}
static Big mul(const Big &a, const Big &b)
{
Big r;
if (a.zero() || b.zero())
return r;
r.d.assign(a.d.size() + b.d.size(), 0);
for (size_t i = 0; i < a.d.size(); i++) {
uint64_t carry = 0;
for (size_t j = 0; j < b.d.size(); j++) {
uint64_t cur = (uint64_t)a.d[i] * b.d[j] + r.d[i + j] + carry;
r.d[i + j] = (uint32_t)cur;
carry = cur >> 32;
}
size_t k = i + b.d.size();
while (carry) {
uint64_t cur = (uint64_t)r.d[k] + carry;
r.d[k] = (uint32_t)cur;
carry = cur >> 32;
k++;
}
}
r.trim();
return r;
}
Big mod(const Big &m) const // 移位减法
{
Big r = *this;
if (m.zero())
return r;
while (r.cmp(m) >= 0) {
size_t shift = r.bits() - m.bits();
Big t = m.shl(shift);
while (t.cmp(r) > 0 && shift > 0) {
shift--;
t = m.shl(shift);
}
r = r.sub(t);
}
return r;
}
};
static Big modpow(const Big &base, const Big &exp, const Big &mod)
{
Big result(1);
Big b = base.mod(mod);
size_t bits = exp.bits();
for (size_t i = 0; i < bits; i++) {
if ((exp.d[i / 32] >> (i % 32)) & 1)
result = Big::mul(result, b).mod(mod);
b = Big::mul(b, b).mod(mod);
}
return result;
}
// ---------------------------------------------------------------- chunk 定义(与 runtime/licensing_manager.h 对齐)
enum
{
CHUNK_VERSION = 0x01,
CHUNK_USER_NAME = 0x02,
CHUNK_EMAIL = 0x03,
CHUNK_HWID = 0x04,
CHUNK_EXP_DATE = 0x05,
CHUNK_RUNNING_TIME = 0x06,
CHUNK_PRODUCT_CODE = 0x07,
CHUNK_USER_DATA = 0x08,
CHUNK_MAX_BUILD = 0x09,
CHUNK_END = 0xFF
};
static void push_date(Bytes &out, uint8_t tag, uint32_t date)
{
out.push_back(tag);
out.push_back((uint8_t)(date >> 24));
out.push_back((uint8_t)(date >> 16));
out.push_back((uint8_t)(date >> 8));
out.push_back((uint8_t)date);
}
static bool parse_date(const char *s, uint32_t &out)
{
if (strlen(s) < 8)
return false;
int y = atoi(std::string(s, 4).c_str());
int m = atoi(std::string(s + 4, 2).c_str());
int d = atoi(std::string(s + 6, 2).c_str());
if (y < 1970 || m < 1 || m > 12 || d < 1 || d > 31)
return false;
out = ((uint32_t)y << 16) | ((uint32_t)m << 8) | (uint32_t)d;
return true;
}
static std::string date_to_string(uint32_t v)
{
char buf[32];
snprintf(buf, sizeof(buf), "%04u-%02u-%02u", v >> 16, (v >> 8) & 0xFF, v & 0xFF);
return buf;
}
// ---------------------------------------------------------------- 简易 XML 属性提取
static bool xml_attr(const std::string &xml, const char *name, std::string &value)
{
std::string key = std::string(name) + "=\"";
size_t pos = xml.find(key);
if (pos == std::string::npos)
return false;
pos += key.size();
size_t end = xml.find('"', pos);
if (end == std::string::npos)
return false;
value = xml.substr(pos, end - pos);
return true;
}
static bool read_file(const char *name, std::string &out)
{
FILE *f = fopen(name, "rb");
if (!f)
return false;
char buf[8192];
size_t got;
while ((got = fread(buf, 1, sizeof(buf), f)) > 0)
out.append(buf, got);
fclose(f);
return true;
}
// ---------------------------------------------------------------- 主流程
static void usage()
{
printf(
"DogProtect keygen\n"
"\n"
" dogkeygen --project <file.dog|license.xml> [options]\n"
" dogkeygen --modulus <base64> --private-exp <base64> [options]\n"
" dogkeygen --verify <serial> --project <file.dog|license.xml>\n"
"\n"
"options:\n"
" --user <name> 客户名(默认 DogProtect User)\n"
" --email <mail> 客户邮箱\n"
" --exp YYYYMMDD 到期日\n"
" --max-build YYYYMMDD 允许运行的最高构建日期\n"
" --running-time <min> 运行时长限制(分钟,1..255)\n"
" --hwid <base64> 绑定硬件 ID(可由 SDK 的 GetCurrentHWID 取得)\n"
" --user-data <hex> 用户数据(首字节是产品 ID,00=不限)\n"
" --product-code <base64> 工程 ProductCode(设了 LockToKey 的代码需要)\n"
" --out <file> 写入文件(默认打印到标准输出)\n"
"\n");
}
int main(int argc, char *argv[])
{
std::string project, modulus_b64, privexp_b64, username = "DogProtect User", email,
hwid_b64, user_data_hex, product_code_b64, out_file, verify_serial;
uint32_t exp_date = 0, max_build = 0;
int running_time = -1;
int serial_version = 1;
for (int i = 1; i < argc; i++) {
std::string a = argv[i];
const char *next = (i + 1 < argc) ? argv[i + 1] : NULL;
if (a == "--help" || a == "-h") { usage(); return 0; }
else if (a == "--project" && next) { project = next; i++; }
else if (a == "--modulus" && next) { modulus_b64 = next; i++; }
else if (a == "--private-exp" && next) { privexp_b64 = next; i++; }
else if (a == "--user" && next) { username = next; i++; }
else if (a == "--email" && next) { email = next; i++; }
else if (a == "--hwid" && next) { hwid_b64 = next; i++; }
else if (a == "--user-data" && next) { user_data_hex = next; i++; }
else if (a == "--product-code" && next) { product_code_b64 = next; i++; }
else if (a == "--out" && next) { out_file = next; i++; }
else if (a == "--verify" && next) { verify_serial = next; i++; }
else if (a == "--exp" && next) { if (!parse_date(next, exp_date)) { printf("bad --exp\n"); return 1; } i++; }
else if (a == "--max-build" && next) { if (!parse_date(next, max_build)) { printf("bad --max-build\n"); return 1; } i++; }
else if (a == "--running-time" && next) { running_time = atoi(next); i++; }
else if (a == "--serial-version" && next) { serial_version = atoi(next); i++; }
else { printf("unknown option: %s\n", a.c_str()); usage(); return 1; }
}
if (!project.empty()) {
std::string xml;
if (!read_file(project.c_str(), xml)) {
printf("cannot read %s\n", project.c_str());
return 1;
}
std::string v;
if (modulus_b64.empty() && xml_attr(xml, "Modulus", v))
modulus_b64 = v;
if (privexp_b64.empty() && xml_attr(xml, "PrivateExp", v))
privexp_b64 = v;
if (product_code_b64.empty() && xml_attr(xml, "ProductCode", v))
product_code_b64 = v;
}
if (modulus_b64.empty()) {
printf("modulus 未知:用 --project 指向带 <LicenseManager Modulus=\"...\"> 的工程/授权文件,或直接给 --modulus\n");
return 1;
}
Bytes modulus = b64_decode(modulus_b64);
if (modulus.empty()) {
printf("modulus base64 解析失败\n");
return 1;
}
Big n = Big::from_bytes_be(&modulus[0], modulus.size());
// ---------- 验签模式 ----------
if (!verify_serial.empty()) {
std::string pub_b64 = modulus_b64;
std::string v;
if (!project.empty() && read_file(project.c_str(), v)) {
std::string tmp;
if (xml_attr(v, "PublicExp", tmp))
pub_b64 = tmp;
}
Bytes pub = b64_decode(pub_b64);
if (pub.empty()) {
printf("PublicExp 缺失\n");
return 1;
}
Big e = Big::from_bytes_be(&pub[0], pub.size());
Bytes sig = b64_decode(verify_serial);
if (sig.empty()) {
printf("序列号不是合法 base64\n");
return 1;
}
Big s = Big::from_bytes_be(&sig[0], sig.size());
Big m = modpow(s, e, n);
Bytes raw = m.to_bytes_be(modulus.size());
if (raw.size() < 3 || raw[0] != 0x00 || raw[1] != 0x02) {
printf("验签失败:解出的块不是 00 02 开头\n");
return 2;
}
size_t pos = 2;
while (pos < raw.size() && raw[pos] != 0)
pos++;
if (pos + 1 >= raw.size()) {
printf("验签失败:填充区没有 0x00 结束符\n");
return 2;
}
pos++;
printf("验签通过(%zu 字节 payload):\n", raw.size() - pos);
size_t i = pos;
while (i < raw.size()) {
uint8_t tag = raw[i++];
if (tag == CHUNK_VERSION) {
printf(" version : %u\n", raw[i]); i += 1;
} else if (tag == CHUNK_EXP_DATE) {
uint32_t v2 = ((uint32_t)raw[i] << 24) | ((uint32_t)raw[i + 1] << 16) | ((uint32_t)raw[i + 2] << 8) | raw[i + 3];
printf(" exp date : %s\n", date_to_string(v2).c_str()); i += 4;
} else if (tag == CHUNK_MAX_BUILD) {
uint32_t v2 = ((uint32_t)raw[i] << 24) | ((uint32_t)raw[i + 1] << 16) | ((uint32_t)raw[i + 2] << 8) | raw[i + 3];
printf(" max build : %s\n", date_to_string(v2).c_str()); i += 4;
} else if (tag == CHUNK_RUNNING_TIME) {
printf(" running time : %u min\n", raw[i]); i += 1;
} else if (tag == CHUNK_PRODUCT_CODE) {
printf(" product code : "); for (int k = 0; k < 8; k++) printf("%02X", raw[i + k]);
printf("\n"); i += 8;
} else if (tag == CHUNK_USER_NAME || tag == CHUNK_EMAIL || tag == CHUNK_HWID || tag == CHUNK_USER_DATA) {
uint8_t len = raw[i]; i++;
const char *label = tag == CHUNK_USER_NAME ? "user name" : tag == CHUNK_EMAIL ? "email" :
tag == CHUNK_HWID ? "hwid" : "user data";
if (tag == CHUNK_USER_NAME || tag == CHUNK_EMAIL) {
printf(" %-14s : %.*s\n", label, len, (const char *)&raw[i]);
} else {
printf(" %-14s : ", label);
for (int k = 0; k < len; k++) printf("%02X", raw[i + k]);
printf("\n");
}
i += len;
} else if (tag == CHUNK_END) {
printf(" checksum : %02X%02X%02X%02X\n", raw[i], raw[i + 1], raw[i + 2], raw[i + 3]);
return 0;
} else {
printf("未知 chunk 0x%02X,停止解析\n", tag);
return 2;
}
}
return 0;
}
// ---------- 签名模式 ----------
if (privexp_b64.empty()) {
printf("私钥缺失:用 --project 指向带 <LicenseManager PrivateExp=\"...\"> 的文件,或直接给 --private-exp\n");
return 1;
}
Bytes privexp = b64_decode(privexp_b64);
if (privexp.empty()) {
printf("PrivateExp base64 解析失败\n");
return 1;
}
Big d = Big::from_bytes_be(&privexp[0], privexp.size());
Bytes payload;
payload.push_back(CHUNK_VERSION);
payload.push_back((uint8_t)serial_version);
if (exp_date)
push_date(payload, CHUNK_EXP_DATE, exp_date);
if (max_build)
push_date(payload, CHUNK_MAX_BUILD, max_build);
if (running_time > 0) {
if (running_time > 255)
running_time = 255;
payload.push_back(CHUNK_RUNNING_TIME);
payload.push_back((uint8_t)running_time);
}
if (!product_code_b64.empty()) {
Bytes pc = b64_decode(product_code_b64);
if (pc.size() == 8) {
payload.push_back(CHUNK_PRODUCT_CODE);
payload.insert(payload.end(), pc.begin(), pc.end());
}
}
if (!username.empty()) {
payload.push_back(CHUNK_USER_NAME);
payload.push_back((uint8_t)username.size());
payload.insert(payload.end(), username.begin(), username.end());
}
if (!email.empty()) {
payload.push_back(CHUNK_EMAIL);
payload.push_back((uint8_t)email.size());
payload.insert(payload.end(), email.begin(), email.end());
}
if (!hwid_b64.empty()) {
Bytes hwid = b64_decode(hwid_b64);
payload.push_back(CHUNK_HWID);
payload.push_back((uint8_t)hwid.size());
payload.insert(payload.end(), hwid.begin(), hwid.end());
}
if (!user_data_hex.empty()) {
Bytes ud;
for (size_t i = 0; i + 1 < user_data_hex.size(); i += 2) {
char h[3] = { user_data_hex[i], user_data_hex[i + 1], 0 };
ud.push_back((uint8_t)strtol(h, NULL, 16));
}
payload.push_back(CHUNK_USER_DATA);
payload.push_back((uint8_t)ud.size());
payload.insert(payload.end(), ud.begin(), ud.end());
}
payload.push_back(CHUNK_END);
// 校验和 = sha1(END 之前的全部字节) 的前 4 字节,倒序写入
uint8_t hash[20];
SHA1 sha;
sha.input(&payload[0], payload.size() - 1);
sha.result(hash);
payload.push_back(hash[3]);
payload.push_back(hash[2]);
payload.push_back(hash[1]);
payload.push_back(hash[0]);
// PKCS#1 v1.5:00 02 || 非零填充 || 00 || payload
size_t total = modulus.size();
if (payload.size() + 11 > total) {
printf("payload 太长(%zu 字节),超过模长 %zu\n", payload.size(), total);
return 1;
}
Bytes block;
block.push_back(0x00);
block.push_back(0x02);
size_t pad_len = total - payload.size() - 3;
for (size_t i = 0; i < pad_len; i++)
block.push_back((uint8_t)(1 + (i * 37) % 254)); // 非零填充,确定可复现
block.push_back(0x00);
block.insert(block.end(), payload.begin(), payload.end());
Big m = Big::from_bytes_be(&block[0], block.size());
Big s = modpow(m, d, n);
Bytes sig = s.to_bytes_be(total);
std::string serial = b64_encode(sig);
if (!out_file.empty()) {
FILE *f = fopen(out_file.c_str(), "wb");
if (!f) { printf("无法写入 %s\n", out_file.c_str()); return 1; }
fwrite(serial.data(), 1, serial.size(), f);
fclose(f);
printf("%s\n", serial.c_str());
printf("(已写入 %s,%zu 字符)\n", out_file.c_str(), serial.size());
} else {
printf("%s\n", serial.c_str());
}
return 0;
}