zhangzengfei
2019-11-18 1698465f3c5e4b5df03f9d9d1a303e7001da9f40
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package licence
 
import (
    "encoding/json"
    "strings"
    "time"
 
    "github.com/shirou/gopsutil/cpu"
    // "github.com/shirou/gopsutil/disk"
    "github.com/shirou/gopsutil/host"
)
 
type Licence struct {
    MachineCode string
    Expires     int64
}
 
const (
    ValidationErrorMalformed        uint32 = iota + 1 // Licence is malformed
    ValidationErrorUnverifiableHost                   // Licence could not be verified because of signing problems
    ValidationErrorExpired                            // Signature validation failed
)
 
func GetMachineCode() string {
    var machineCode string
 
    // CPU
    if cpu, err := cpu.Info(); err == nil {
        for _, c := range cpu {
            strings.Join([]string{machineCode, c.String()}, "-")
        }
    }
 
    // // Disk
    // if diskInfo, err := disk.Partitions(false); err == nil {
    //     for _, d := range diskInfo {
    //         diskSerialNumber := disk.GetDiskSerialNumber(d.Device)
    //         strings.Join([]string{machineCode, diskSerialNumber}, "-")
    //     }
    // }
 
    // Host
    if host, err := host.Info(); err == nil {
        strings.Join([]string{machineCode, host.HostID}, "-")
    }
 
    return GetMd5String(machineCode, true, false)
}
 
func GenerateLicence(machineCode, timeOut, key string) string {
    timeLayout := "2006-01-02 15:04:05"  //转化所需模板
    loc, _ := time.LoadLocation("Local") //获取时区
    tmp, _ := time.ParseInLocation(timeLayout, timeOut, loc)
    timestamp := tmp.Unix()
 
    licence := Licence{machineCode, timestamp}
 
    json, _ := json.Marshal(licence)
    return AESEncodeStr(json, key)
}
 
func VerifyLicence(licenceCode, key string) uint32 {
    decodeData := AESDecodeStr(licenceCode, key)
    if decodeData == nil {
        return ValidationErrorMalformed
    }
 
    var licence Licence
 
    if err := json.Unmarshal(decodeData, &licence); err != nil {
        return ValidationErrorMalformed
    }
 
    code := GetMachineCode()
    if licence.MachineCode != code {
        return ValidationErrorUnverifiableHost
    }
 
    now := time.Now().Unix()
    if now > licence.Expires {
        return ValidationErrorExpired
    }
 
    return 0
}