Files
verify/backend/internal/doglic/sign.go
T
Cmake f51a41db24 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」的场景测试用
2026-11-23 18:16:52 +08:00

270 lines
7.4 KiB
Go
Raw 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.
// 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")
}