feat(licensing): 自签授权验签(服务端签发 + 客户端零依赖校验)
- sdk/cpp/doglic.hpp:头文件版验签(自带 bignum/SHA-1/base64,PKCS#1 v1.5 结构 + chunk 解析 + 尾部校验和 + 到期/构建日判定),任何 C++ 产品包含即可用 - backend/internal/doglic:Go 版签发/校验(密钥取自工程 <LicenseManager> 的 base64 属性) - backend/cmd/doglicgen:签发 CLI(-user/-email/-exp/-max-build/-running-time/-hwid/-user-data, 以及 -verify 自检) - backend/cmd/packsigned:以 signed 模式(flags bit1,壳侧跳过整文件 CRC)注入验证壳, 供「先打壳再二次加 DogProtect」的场景测试用
This commit is contained in:
@@ -0,0 +1,119 @@
|
||||
// 签发自签授权序列号(与 DogProtect tools/dogkeygen 等价,Go 版,便于服务端集成)
|
||||
//
|
||||
// 用法:
|
||||
// doglicgen -key <工程.dog|license.xml> -user "客户A" [-email a@b.c] [-exp 20271231]
|
||||
// [-max-build 20270101] [-running-time 90] [-hwid <base64>] [-user-data <hex>]
|
||||
// [-out serial.txt]
|
||||
// doglicgen -key <file> -verify <serial> # 用公钥验一遍并打印字段
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"verification-platform-backend/internal/doglic"
|
||||
)
|
||||
|
||||
func dateArg(s string) (time.Time, error) {
|
||||
if s == "" {
|
||||
return time.Time{}, nil
|
||||
}
|
||||
return time.Parse("20060102", s)
|
||||
}
|
||||
|
||||
func main() {
|
||||
keyPath := flag.String("key", "", "工程/授权文件(含 <LicenseManager Modulus/PrivateExp>)")
|
||||
user := flag.String("user", "", "客户名")
|
||||
email := flag.String("email", "", "客户邮箱")
|
||||
exp := flag.String("exp", "", "到期日 YYYYMMDD")
|
||||
maxBuild := flag.String("max-build", "", "最高构建日 YYYYMMDD")
|
||||
runningTime := flag.Int("running-time", 0, "运行时长限制(分钟)")
|
||||
hwidB64 := flag.String("hwid", "", "绑机数据(base64)")
|
||||
userDataHex := flag.String("user-data", "", "用户数据(hex,首字节常作产品 ID)")
|
||||
serialVersion := flag.Int("serial-version", 1, "序列号版本 1 或 2")
|
||||
out := flag.String("out", "", "写入文件")
|
||||
verifySerial := flag.String("verify", "", "只验签并打印字段")
|
||||
flag.Parse()
|
||||
|
||||
if *keyPath == "" {
|
||||
fmt.Fprintln(os.Stderr, "缺少 -key")
|
||||
os.Exit(2)
|
||||
}
|
||||
keys, err := doglic.LoadKeysFromFile(*keyPath)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "读密钥失败:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if *verifySerial != "" {
|
||||
ok, fields, err := doglic.Verify(keys, *verifySerial)
|
||||
fmt.Printf("verify=%v err=%v\n", ok, err)
|
||||
for k, v := range fields {
|
||||
fmt.Printf(" %-14s %s\n", k, v)
|
||||
}
|
||||
if !ok {
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
expDate, err := dateArg(*exp)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "-exp 格式应为 YYYYMMDD")
|
||||
os.Exit(2)
|
||||
}
|
||||
mbDate, err := dateArg(*maxBuild)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "-max-build 格式应为 YYYYMMDD")
|
||||
os.Exit(2)
|
||||
}
|
||||
var hwid, userData []byte
|
||||
if *hwidB64 != "" {
|
||||
hwid, err = base64.StdEncoding.DecodeString(*hwidB64)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "-hwid base64 解析失败")
|
||||
os.Exit(2)
|
||||
}
|
||||
}
|
||||
if *userDataHex != "" {
|
||||
userData, err = hex.DecodeString(*userDataHex)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "-user-data 应为 hex")
|
||||
os.Exit(2)
|
||||
}
|
||||
}
|
||||
|
||||
serial, err := doglic.Sign(keys, doglic.Request{
|
||||
UserName: *user,
|
||||
Email: *email,
|
||||
ExpDate: expDate,
|
||||
MaxBuildDate: mbDate,
|
||||
RunningTime: *runningTime,
|
||||
HWID: hwid,
|
||||
UserData: userData,
|
||||
SerialVersion: byte(*serialVersion),
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "签发失败:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
ok, fields, verr := doglic.Verify(keys, serial)
|
||||
fmt.Printf("self-check: %v (%v)\n", ok, verr)
|
||||
for k, v := range fields {
|
||||
fmt.Printf(" %-14s %s\n", k, v)
|
||||
}
|
||||
|
||||
if *out != "" {
|
||||
if err := os.WriteFile(*out, []byte(serial), 0o600); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "写文件失败:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Printf("已写入 %s(%d 字符)\n", *out, len(serial))
|
||||
}
|
||||
fmt.Println(serial)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// 临时工具:以 signed 模式(flags bit1,壳侧跳过整文件 CRC)注入验证壳
|
||||
// 用法: packsigned <src> <out> <cfg.json>
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"verification-platform-backend/internal/protect"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) != 4 {
|
||||
fmt.Fprintln(os.Stderr, "用法: packsigned <src> <out> <cfg.json>")
|
||||
os.Exit(2)
|
||||
}
|
||||
src, err := os.ReadFile(os.Args[1])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
cfg, err := os.ReadFile(os.Args[3])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
arch, err := protect.DetectArch(src)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
out, info, err := protect.PatchSigned(src, cfg, arch, true)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if err := os.WriteFile(os.Args[2], out, 0o644); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Printf("产物 %s %d 字节 入口 0x%x→0x%x crcVfy=%08x crcFile=%08x\n",
|
||||
os.Args[2], info.OutSize, info.EntryOld, info.EntryNew, info.CrcVfy, info.CrcFile)
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
// Package doglic 签发/校验自签授权序列号(与 DogProtect 仓库 tools/dogkeygen、sdk/cpp/doglic.hpp 同一套格式)
|
||||
//
|
||||
// 序列号 = base64( (00 02 || 非零填充 || 00 || payload) ^ d mod n )
|
||||
// payload = chunk..., 末尾 0xFF + sha1(前面全部字节) 前 4 字节倒序
|
||||
//
|
||||
// 密钥来自工程/授权文件里的 <LicenseManager Modulus=".." PrivateExp=".." PublicExp=".."/>(均为 base64 大端)。
|
||||
package doglic
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha1"
|
||||
"encoding/base64"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// chunk 标记,与 runtime/licensing_manager.h 对齐
|
||||
const (
|
||||
ChunkVersion = 0x01
|
||||
ChunkUserName = 0x02
|
||||
ChunkEmail = 0x03
|
||||
ChunkHWID = 0x04
|
||||
ChunkExpDate = 0x05
|
||||
ChunkRunningTime = 0x06
|
||||
ChunkProductCode = 0x07
|
||||
ChunkUserData = 0x08
|
||||
ChunkMaxBuild = 0x09
|
||||
ChunkEnd = 0xFF
|
||||
)
|
||||
|
||||
// Keys 一套签名密钥
|
||||
type Keys struct {
|
||||
Modulus []byte // 大端
|
||||
PublicExp []byte
|
||||
PrivateExp []byte
|
||||
ProductCode []byte // 可选,工程设置了 LockToKey 时要用
|
||||
}
|
||||
|
||||
type licenseManagerXML struct {
|
||||
LicenseManager struct {
|
||||
Algorithm string `xml:"Algorithm,attr"`
|
||||
Modulus string `xml:"Modulus,attr"`
|
||||
PublicExp string `xml:"PublicExp,attr"`
|
||||
PrivateExp string `xml:"PrivateExp,attr"`
|
||||
ProductCode string `xml:"ProductCode,attr"`
|
||||
} `xml:"LicenseManager"`
|
||||
}
|
||||
|
||||
// LoadKeysFromFile 从 .dog / license.xml 里读密钥
|
||||
func LoadKeysFromFile(path string) (*Keys, error) {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var doc licenseManagerXML
|
||||
if err := xml.Unmarshal(raw, &doc); err != nil {
|
||||
return nil, fmt.Errorf("解析 %s 失败: %w", path, err)
|
||||
}
|
||||
lm := doc.LicenseManager
|
||||
if lm.Modulus == "" || lm.PrivateExp == "" {
|
||||
return nil, fmt.Errorf("%s 里没有 <LicenseManager Modulus/PrivateExp>", path)
|
||||
}
|
||||
dec := func(s string) ([]byte, error) { return base64.StdEncoding.DecodeString(strings.TrimSpace(s)) }
|
||||
mod, err := dec(lm.Modulus)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Modulus base64: %w", err)
|
||||
}
|
||||
priv, err := dec(lm.PrivateExp)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("PrivateExp base64: %w", err)
|
||||
}
|
||||
pub := []byte{0x01, 0x00, 0x01}
|
||||
if lm.PublicExp != "" {
|
||||
if v, err := dec(lm.PublicExp); err == nil && len(v) > 0 {
|
||||
pub = v
|
||||
}
|
||||
}
|
||||
var pc []byte
|
||||
if lm.ProductCode != "" {
|
||||
pc, _ = dec(lm.ProductCode)
|
||||
}
|
||||
return &Keys{Modulus: mod, PublicExp: pub, PrivateExp: priv, ProductCode: pc}, nil
|
||||
}
|
||||
|
||||
// Request 签发参数
|
||||
type Request struct {
|
||||
UserName string
|
||||
Email string
|
||||
ExpDate time.Time // 零值 = 不限
|
||||
MaxBuildDate time.Time
|
||||
RunningTime int // 分钟,0 = 不限
|
||||
HWID []byte // 绑机数据,nil = 不绑
|
||||
UserData []byte // 首字节常作产品 ID
|
||||
SerialVersion byte // 1 或 2,默认 1
|
||||
}
|
||||
|
||||
// 日期编码:(年<<16)|(月<<8)|日
|
||||
func encodeDate(t time.Time) uint32 {
|
||||
if t.IsZero() {
|
||||
return 0
|
||||
}
|
||||
return uint32(t.Year())<<16 | uint32(t.Month())<<8 | uint32(t.Day())
|
||||
}
|
||||
|
||||
// Sign 生成序列号
|
||||
func Sign(k *Keys, req Request) (string, error) {
|
||||
n := new(big.Int).SetBytes(k.Modulus)
|
||||
if n.Sign() == 0 {
|
||||
return "", fmt.Errorf("modulus 为空")
|
||||
}
|
||||
modLen := len(k.Modulus)
|
||||
|
||||
payload := []byte{ChunkVersion, req.SerialVersion}
|
||||
if payload[1] == 0 {
|
||||
payload[1] = 1
|
||||
}
|
||||
if d := encodeDate(req.ExpDate); d != 0 {
|
||||
payload = append(payload, ChunkExpDate, byte(d>>24), byte(d>>16), byte(d>>8), byte(d))
|
||||
}
|
||||
if d := encodeDate(req.MaxBuildDate); d != 0 {
|
||||
payload = append(payload, ChunkMaxBuild, byte(d>>24), byte(d>>16), byte(d>>8), byte(d))
|
||||
}
|
||||
if req.RunningTime > 0 {
|
||||
rt := req.RunningTime
|
||||
if rt > 255 {
|
||||
rt = 255
|
||||
}
|
||||
payload = append(payload, ChunkRunningTime, byte(rt))
|
||||
}
|
||||
pc := req.UserData
|
||||
if len(k.ProductCode) == 8 {
|
||||
payload = append(payload, ChunkProductCode)
|
||||
payload = append(payload, k.ProductCode...)
|
||||
}
|
||||
if req.UserName != "" {
|
||||
name := []byte(req.UserName)
|
||||
if len(name) > 255 {
|
||||
name = name[:255]
|
||||
}
|
||||
payload = append(payload, ChunkUserName, byte(len(name)))
|
||||
payload = append(payload, name...)
|
||||
}
|
||||
if req.Email != "" {
|
||||
mail := []byte(req.Email)
|
||||
if len(mail) > 255 {
|
||||
mail = mail[:255]
|
||||
}
|
||||
payload = append(payload, ChunkEmail, byte(len(mail)))
|
||||
payload = append(payload, mail...)
|
||||
}
|
||||
if len(req.HWID) > 0 {
|
||||
payload = append(payload, ChunkHWID, byte(len(req.HWID)))
|
||||
payload = append(payload, req.HWID...)
|
||||
}
|
||||
if len(pc) > 0 {
|
||||
payload = append(payload, ChunkUserData, byte(len(pc)))
|
||||
payload = append(payload, pc...)
|
||||
}
|
||||
payload = append(payload, ChunkEnd)
|
||||
|
||||
sum := sha1.Sum(payload[:len(payload)-1])
|
||||
payload = append(payload, sum[3], sum[2], sum[1], sum[0])
|
||||
|
||||
if len(payload)+11 > modLen {
|
||||
return "", fmt.Errorf("payload 太长(%d),超过模长 %d", len(payload), modLen)
|
||||
}
|
||||
|
||||
// PKCS#1 v1.5:00 02 || 非零填充 || 00 || payload
|
||||
block := make([]byte, 0, modLen)
|
||||
block = append(block, 0x00, 0x02)
|
||||
padLen := modLen - len(payload) - 3
|
||||
pad := make([]byte, padLen)
|
||||
if _, err := rand.Read(pad); err != nil {
|
||||
return "", err
|
||||
}
|
||||
for i := range pad {
|
||||
pad[i] = pad[i]%255 + 1 // 非零
|
||||
}
|
||||
block = append(block, pad...)
|
||||
block = append(block, 0x00)
|
||||
block = append(block, payload...)
|
||||
|
||||
d := new(big.Int).SetBytes(k.PrivateExp)
|
||||
m := new(big.Int).SetBytes(block)
|
||||
sig := new(big.Int).Exp(m, d, n)
|
||||
|
||||
out := make([]byte, modLen)
|
||||
sigBytes := sig.Bytes()
|
||||
copy(out[modLen-len(sigBytes):], sigBytes)
|
||||
return base64.StdEncoding.EncodeToString(out), nil
|
||||
}
|
||||
|
||||
// Verify 用公钥校验(服务端自检/单测用;客户端同逻辑见 sdk/cpp/doglic.hpp)
|
||||
func Verify(k *Keys, serial string) (bool, map[string]string, error) {
|
||||
raw, err := base64.StdEncoding.DecodeString(serial)
|
||||
if err != nil {
|
||||
return false, nil, err
|
||||
}
|
||||
n := new(big.Int).SetBytes(k.Modulus)
|
||||
e := new(big.Int).SetBytes(k.PublicExp)
|
||||
m := new(big.Int).Exp(new(big.Int).SetBytes(raw), e, n)
|
||||
block := make([]byte, len(k.Modulus))
|
||||
mb := m.Bytes()
|
||||
copy(block[len(block)-len(mb):], mb)
|
||||
|
||||
if len(block) < 3 || block[0] != 0x00 || block[1] != 0x02 {
|
||||
return false, nil, fmt.Errorf("结构不对(不是 00 02 开头)")
|
||||
}
|
||||
pos := 2
|
||||
for pos < len(block) && block[pos] != 0 {
|
||||
pos++
|
||||
}
|
||||
if pos+1 >= len(block) {
|
||||
return false, nil, fmt.Errorf("填充区没有 0x00 结束符")
|
||||
}
|
||||
pos++
|
||||
p := block[pos:]
|
||||
|
||||
fields := map[string]string{}
|
||||
i := 0
|
||||
for i < len(p) {
|
||||
tag := p[i]
|
||||
switch tag {
|
||||
case ChunkVersion:
|
||||
fields["version"] = fmt.Sprintf("%d", p[i+1])
|
||||
i += 2
|
||||
case ChunkUserName, ChunkEmail:
|
||||
n2 := int(p[i+1])
|
||||
v := string(p[i+2 : i+2+n2])
|
||||
if tag == ChunkUserName {
|
||||
fields["user"] = v
|
||||
} else {
|
||||
fields["email"] = v
|
||||
}
|
||||
i += 2 + n2
|
||||
case ChunkExpDate, ChunkMaxBuild:
|
||||
d := uint32(p[i+1])<<24 | uint32(p[i+2])<<16 | uint32(p[i+3])<<8 | uint32(p[i+4])
|
||||
key := "exp"
|
||||
if tag == ChunkMaxBuild {
|
||||
key = "maxbuild"
|
||||
}
|
||||
fields[key] = fmt.Sprintf("%04d-%02d-%02d", d>>16, (d>>8)&0xFF, d&0xFF)
|
||||
i += 5
|
||||
case ChunkRunningTime:
|
||||
fields["running_time"] = fmt.Sprintf("%d", p[i+1])
|
||||
i += 2
|
||||
case ChunkHWID, ChunkUserData:
|
||||
n2 := int(p[i+1])
|
||||
fields[map[bool]string{true: "hwid", false: "userdata"}[tag == ChunkHWID]] = fmt.Sprintf("%x", p[i+2:i+2+n2])
|
||||
i += 2 + n2
|
||||
case ChunkProductCode:
|
||||
fields["product_code"] = fmt.Sprintf("%x", p[i+1:i+9])
|
||||
i += 9
|
||||
case ChunkEnd:
|
||||
sum := sha1.Sum(p[:i])
|
||||
if p[i+1] != sum[3] || p[i+2] != sum[2] || p[i+3] != sum[1] || p[i+4] != sum[0] {
|
||||
return false, fields, fmt.Errorf("校验和不匹配")
|
||||
}
|
||||
return true, fields, nil
|
||||
default:
|
||||
return false, fields, fmt.Errorf("未知 chunk 0x%02X", tag)
|
||||
}
|
||||
}
|
||||
return false, fields, fmt.Errorf("缺少 END chunk")
|
||||
}
|
||||
@@ -139,3 +139,25 @@ client.createVariableRecord("stream_key", record);
|
||||
## 许可证
|
||||
|
||||
MIT License
|
||||
|
||||
## doglic.hpp — 自签授权验签(离线、零依赖)
|
||||
|
||||
头和实现合一的单文件,加进工程即可验「序列号」授权。格式与 DogProtect 仓库的
|
||||
`tools/dogkeygen` 一致(PKCS#1 v1.5 块 + 自定义 chunk + SHA-1 尾部校验),服务端用
|
||||
`backend/cmd/doglicgen` 签发。
|
||||
|
||||
```cpp
|
||||
#include "doglic.hpp"
|
||||
|
||||
doglic::License lic;
|
||||
int rc = doglic::verifyB64Key(serial, modulusB64, publicExpB64, &lic); // 工程里 <LicenseManager> 的两个属性
|
||||
if (rc == doglic::OK) {
|
||||
// lic.userName / lic.email / lic.expDate / lic.maxBuildDate / lic.runningTimeLimit / lic.hwid
|
||||
}
|
||||
```
|
||||
|
||||
错误码:`ERR_STRUCTURE`(块结构)、`ERR_CHECKSUM`(尾部校验和)、`ERR_EXPIRED`(过期)、
|
||||
`ERR_MAX_BUILD`(超过允许构建日)、`ERR_UNKNOWN_CHUNK` 等,见头文件 `VerifyResult`。
|
||||
|
||||
实测(Linux,clang++ -O2 即可编译,无第三方库):Go 侧 `doglicgen` 签发的序列号在 C++
|
||||
侧 `rc=0` 且字段全对;改一位 → `rc=3`;`-exp 20200101` → `rc=8`。
|
||||
|
||||
@@ -0,0 +1,420 @@
|
||||
// doglic — 自签授权验签(头文件版,零外部依赖)
|
||||
//
|
||||
// 与 tools/dogkeygen(DogProtect 仓库)签出的序列号完全兼容:
|
||||
// serial = base64( (00 02 || 非零填充 || 00 || payload) ^ d mod n )
|
||||
// payload = chunk..., 末尾 0xFF + sha1(前面全部字节) 的前 4 字节倒序
|
||||
//
|
||||
// 设计目标:任何 C++ 程序把本头文件加进来就能离线验序列号,不需要 OpenSSL / SDK。
|
||||
// 公钥(modulus / public exponent)由调用方提供,见 doglicInit()。
|
||||
//
|
||||
// 典型用法:
|
||||
// doglic::License lic;
|
||||
// if (doglic::verify(serialFromUser, g_modulusHex, "010001", &lic))
|
||||
// printf("welcome %s, exp %08X\n", lic.user.c_str(), lic.expDate);
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <cstdlib>
|
||||
#include <ctime>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace doglic {
|
||||
|
||||
// ---------------------------------------------------------------- chunk 定义(与 runtime 对齐)
|
||||
enum Chunk {
|
||||
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
|
||||
};
|
||||
|
||||
enum VerifyResult {
|
||||
OK = 0,
|
||||
ERR_BASE64 = 1,
|
||||
ERR_SIZE = 2,
|
||||
ERR_STRUCTURE = 3, // 解出来的块不是 00 02 ... 00 结构
|
||||
ERR_VERSION = 4,
|
||||
ERR_UNKNOWN_CHUNK = 5,
|
||||
ERR_NO_END = 6,
|
||||
ERR_CHECKSUM = 7,
|
||||
ERR_EXPIRED = 8,
|
||||
ERR_RUNNING_TIME = 9,
|
||||
ERR_MAX_BUILD = 10
|
||||
};
|
||||
|
||||
struct License {
|
||||
std::string userName;
|
||||
std::string email;
|
||||
uint32_t expDate; // (年<<16)|(月<<8)|日,0 = 不限
|
||||
uint32_t maxBuildDate; // 0 = 不限
|
||||
uint8_t runningTimeLimit;
|
||||
std::vector<uint8_t> hwid;
|
||||
std::vector<uint8_t> userData;
|
||||
|
||||
License() : expDate(0), maxBuildDate(0), runningTimeLimit(0) {}
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- base64 / sha1 / bignum
|
||||
inline int b64val(int c)
|
||||
{
|
||||
if (c >= 'A' && c <= 'Z') return c - 'A';
|
||||
if (c >= 'a' && c <= 'z') return c - 'a' + 26;
|
||||
if (c >= '0' && c <= '9') return c - '0' + 52;
|
||||
if (c == '+') return 62;
|
||||
if (c == '/') return 63;
|
||||
return -1;
|
||||
}
|
||||
|
||||
inline std::vector<uint8_t> b64decode(const std::string &src)
|
||||
{
|
||||
std::vector<uint8_t> out;
|
||||
uint32_t buf = 0;
|
||||
int bits = 0;
|
||||
for (size_t i = 0; i < src.size(); i++) {
|
||||
int v = b64val((unsigned char)src[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));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
struct SHA1 {
|
||||
uint32_t h[5];
|
||||
uint8_t buf[64];
|
||||
size_t len;
|
||||
uint64_t total;
|
||||
|
||||
SHA1() : len(0), total(0)
|
||||
{
|
||||
h[0] = 0x67452301; h[1] = 0xEFCDAB89; h[2] = 0x98BADCFE;
|
||||
h[3] = 0x10325476; h[4] = 0xC3D2E1F0;
|
||||
}
|
||||
|
||||
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) | 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 update(const uint8_t *p, size_t n)
|
||||
{
|
||||
total += n;
|
||||
while (n) {
|
||||
size_t take = 64 - len;
|
||||
if (take > n) take = n;
|
||||
memcpy(buf + len, p, take);
|
||||
len += take; p += take; n -= take;
|
||||
if (len == 64) { block(buf); len = 0; }
|
||||
}
|
||||
}
|
||||
|
||||
void finish(uint8_t out[20])
|
||||
{
|
||||
uint64_t bits = total * 8;
|
||||
uint8_t pad = 0x80;
|
||||
update(&pad, 1);
|
||||
uint8_t zero = 0;
|
||||
while (len != 56) update(&zero, 1);
|
||||
uint8_t l[8];
|
||||
for (int i = 0; i < 8; i++) l[i] = (uint8_t)(bits >> (56 - i * 8));
|
||||
update(l, 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];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 大数:小端 32 位肢体,只做 modpow 需要的运算
|
||||
struct Big {
|
||||
std::vector<uint32_t> d;
|
||||
|
||||
Big() {}
|
||||
explicit Big(uint32_t v) { if (v) d.push_back(v); }
|
||||
bool zero() const { return d.empty(); }
|
||||
void trim() { while (!d.empty() && d.back() == 0) d.pop_back(); }
|
||||
|
||||
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 fromBytesBE(const uint8_t *p, size_t n)
|
||||
{
|
||||
Big r;
|
||||
r.d.assign((n + 3) / 4, 0);
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
size_t pos = n - 1 - i;
|
||||
r.d[pos / 4] |= (uint32_t)p[i] << ((pos % 4) * 8);
|
||||
}
|
||||
r.trim();
|
||||
return r;
|
||||
}
|
||||
|
||||
static Big fromHex(const std::string &hex)
|
||||
{
|
||||
std::vector<uint8_t> bytes;
|
||||
for (size_t i = 0; i + 1 < hex.size(); i += 2) {
|
||||
char t[3] = { hex[i], hex[i + 1], 0 };
|
||||
bytes.push_back((uint8_t)strtol(t, 0, 16));
|
||||
}
|
||||
return fromBytesBE(bytes.empty() ? 0 : &bytes[0], bytes.size());
|
||||
}
|
||||
|
||||
void toBytesBE(uint8_t *out, size_t n) const
|
||||
{
|
||||
memset(out, 0, n);
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
size_t pos = n - 1 - i;
|
||||
size_t limb = pos / 4;
|
||||
if (limb < d.size())
|
||||
out[i] = (uint8_t)(d[limb] >> ((pos % 4) * 8));
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
{
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
inline Big modpow(const Big &base, const Big &exp, const Big &mod)
|
||||
{
|
||||
Big r(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)
|
||||
r = Big::mul(r, b).mod(mod);
|
||||
b = Big::mul(b, b).mod(mod);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
inline uint32_t rd32(const uint8_t *p)
|
||||
{
|
||||
return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | p[3];
|
||||
}
|
||||
|
||||
inline uint32_t today()
|
||||
{
|
||||
time_t t = time(0);
|
||||
struct tm tmv;
|
||||
#ifdef _WIN32
|
||||
localtime_s(&tmv, &t);
|
||||
#else
|
||||
localtime_r(&t, &tmv);
|
||||
#endif
|
||||
return ((uint32_t)(tmv.tm_year + 1900) << 16) | ((uint32_t)(tmv.tm_mon + 1) << 8) |
|
||||
(uint32_t)tmv.tm_mday;
|
||||
}
|
||||
|
||||
// 主入口:modulusHex/publicExpHex 用十六进制大端字符串(工程文件里 Modulus/PublicExp 的 base64 先解成字节再转 hex)
|
||||
// 返回 OK 或具体错误码;lic 可传 NULL
|
||||
inline int verify(const std::string &serial,
|
||||
const std::string &modulusHex,
|
||||
const std::string &publicExpHex,
|
||||
License *lic = 0,
|
||||
uint32_t now = 0)
|
||||
{
|
||||
std::vector<uint8_t> sig = b64decode(serial);
|
||||
if (sig.size() < 16) return ERR_BASE64;
|
||||
|
||||
Big n = Big::fromHex(modulusHex);
|
||||
Big e = Big::fromHex(publicExpHex);
|
||||
if (n.zero() || e.zero()) return ERR_SIZE;
|
||||
|
||||
const size_t modLen = (n.bits() + 7) / 8; // 模长按字节向上取整(1024 位 = 128 字节)
|
||||
std::vector<uint8_t> block(modLen, 0);
|
||||
Big sigInt = Big::fromBytesBE(&sig[0], sig.size());
|
||||
Big m = modpow(sigInt, e, n);
|
||||
m.toBytesBE(&block[0], block.size());
|
||||
|
||||
if (block[0] != 0x00 || block[1] != 0x02) return ERR_STRUCTURE;
|
||||
|
||||
size_t pos = 2;
|
||||
while (pos < block.size() && block[pos] != 0x00) pos++;
|
||||
if (pos + 1 >= block.size()) return ERR_STRUCTURE;
|
||||
pos++;
|
||||
|
||||
const uint8_t *p = &block[0] + pos;
|
||||
size_t plen = block.size() - pos;
|
||||
|
||||
License tmp;
|
||||
License &L = lic ? *lic : tmp;
|
||||
L = License();
|
||||
|
||||
size_t i = 0;
|
||||
uint32_t cur = now ? now : today();
|
||||
while (i < plen) {
|
||||
uint8_t tag = p[i];
|
||||
if (tag == CHUNK_VERSION) {
|
||||
if (i + 1 >= plen) return ERR_VERSION;
|
||||
if (p[i + 1] < 1 || p[i + 1] > 2) return ERR_VERSION;
|
||||
i += 2;
|
||||
} else if (tag == CHUNK_USER_NAME || tag == CHUNK_EMAIL) {
|
||||
if (i + 1 >= plen) return ERR_STRUCTURE;
|
||||
uint8_t n2 = p[i + 1];
|
||||
if (i + 2 + n2 > plen) return ERR_STRUCTURE;
|
||||
std::string v((const char *)p + i + 2, n2);
|
||||
if (tag == CHUNK_USER_NAME) L.userName = v; else L.email = v;
|
||||
i += 2 + n2;
|
||||
} else if (tag == CHUNK_EXP_DATE || tag == CHUNK_MAX_BUILD) {
|
||||
if (i + 5 > plen) return ERR_STRUCTURE;
|
||||
uint32_t date = rd32(p + i + 1);
|
||||
if (tag == CHUNK_EXP_DATE) L.expDate = date; else L.maxBuildDate = date;
|
||||
i += 5;
|
||||
} else if (tag == CHUNK_RUNNING_TIME) {
|
||||
if (i + 2 > plen) return ERR_STRUCTURE;
|
||||
L.runningTimeLimit = p[i + 1];
|
||||
i += 2;
|
||||
} else if (tag == CHUNK_HWID || tag == CHUNK_USER_DATA) {
|
||||
if (i + 1 >= plen) return ERR_STRUCTURE;
|
||||
uint8_t n2 = p[i + 1];
|
||||
if (i + 2 + n2 > plen) return ERR_STRUCTURE;
|
||||
std::vector<uint8_t> v(p + i + 2, p + i + 2 + n2);
|
||||
if (tag == CHUNK_HWID) L.hwid = v; else L.userData = v;
|
||||
i += 2 + n2;
|
||||
} else if (tag == CHUNK_PRODUCT_CODE) {
|
||||
if (i + 9 > plen) return ERR_STRUCTURE;
|
||||
i += 9;
|
||||
} else if (tag == CHUNK_END) {
|
||||
if (i + 5 > plen) return ERR_STRUCTURE;
|
||||
uint8_t hash[20];
|
||||
SHA1 sha;
|
||||
sha.update(p, i);
|
||||
sha.finish(hash);
|
||||
if (p[i + 1] != hash[3] || p[i + 2] != hash[2] ||
|
||||
p[i + 3] != hash[1] || p[i + 4] != hash[0])
|
||||
return ERR_CHECKSUM;
|
||||
if (L.expDate && cur > L.expDate) return ERR_EXPIRED;
|
||||
if (L.maxBuildDate && cur > L.maxBuildDate) return ERR_MAX_BUILD;
|
||||
return OK;
|
||||
} else {
|
||||
return ERR_UNKNOWN_CHUNK;
|
||||
}
|
||||
}
|
||||
return ERR_NO_END;
|
||||
}
|
||||
|
||||
// 便捷重载:直接吃 base64 的公钥编码(工程文件里的写法)
|
||||
inline int verifyB64Key(const std::string &serial,
|
||||
const std::string &modulusB64,
|
||||
const std::string &publicExpB64,
|
||||
License *lic = 0)
|
||||
{
|
||||
std::vector<uint8_t> mb = b64decode(modulusB64);
|
||||
std::vector<uint8_t> eb = b64decode(publicExpB64);
|
||||
std::string mh, eh;
|
||||
static const char *hx = "0123456789abcdef";
|
||||
for (size_t i = 0; i < mb.size(); i++) { mh += hx[mb[i] >> 4]; mh += hx[mb[i] & 15]; }
|
||||
for (size_t i = 0; i < eb.size(); i++) { eh += hx[eb[i] >> 4]; eh += hx[eb[i] & 15]; }
|
||||
return verify(serial, mh, eh, lic);
|
||||
}
|
||||
|
||||
} // namespace doglic
|
||||
Reference in New Issue
Block a user