package licence import ( "encoding/base64" "encoding/json" "io/ioutil" "os" "time" ) type RegisterCode struct { MachineCode string Company string Email string Phone string Version string } type Licence struct { RegCode RegisterCode Expires int64 Timestamp int64 } const ( ValidationErrorDecrypt uint32 = iota + 1 // Licence is malformed ValidationErrorUnverifiableHost // Host unauthorized ValidationErrorExpired // Signature expired ValidationErrorMalformed Version = "1.0.1" aesKey = "www.aiotlink.com" ) func GetRegisterCode(company, email, phone string) string { mCode := GetMachineCode() regCode := RegisterCode{mCode, company, email, phone, Version} json, _ := json.Marshal(regCode) return AESEncodeStr(json, aesKey) } func DecryptRegisterCode(regCode string) []byte { return AESDecodeStr(regCode, aesKey) } func GenerateLicence(regCode, timeOut string, privateKey []byte) (string, error) { timeLayout := "2006-01-02 15:04:05" //转化所需模板 loc, _ := time.LoadLocation("Local") //获取时区 tmp, _ := time.ParseInLocation(timeLayout, timeOut, loc) exp := tmp.Unix() now := time.Now().Unix() regCodeText := AESDecodeStr(regCode, aesKey) var registerCode RegisterCode if err := json.Unmarshal(regCodeText, ®isterCode); err != nil { return "", err } licence := Licence{registerCode, exp, now} json, err := json.Marshal(licence) if err != nil { return "", err } RSA := &RSASecurity{} if err := RSA.SetPrivateKey(privateKey); err != nil { return "", err } licenceHex, err := RSA.PriKeyENCTYPT(json) if err != nil { return "", err } licenceText := base64.StdEncoding.EncodeToString(licenceHex) return licenceText, nil } func DecryptLicence(licencePath, publicKeyPath string) ([]byte, error) { var publicKey, licenceCode []byte var fdLic, fdPub *os.File var err error // 读取Licence File fdLic, err = os.Open(licencePath) if err != nil { return nil, err } defer fdLic.Close() licenceCode, err = ioutil.ReadAll(fdLic) if err != nil { return nil, err } // 读取公钥 fdPub, err = os.Open(publicKeyPath) if err != nil { return nil, err } defer fdPub.Close() publicKey, err = ioutil.ReadAll(fdPub) if err != nil { return nil, err } RSA := &RSASecurity{} if err := RSA.SetPublicKey(publicKey); err != nil { return nil, err } licenceHex, _ := base64.StdEncoding.DecodeString(string(licenceCode)) return RSA.PubKeyDECRYPT(licenceHex) } func VerifyLicence(licencePath, publicKeyPath string) uint32 { licenceText, err := DecryptLicence(licencePath, publicKeyPath) if err != nil { return ValidationErrorDecrypt } var licence Licence if err := json.Unmarshal(licenceText, &licence); err != nil { return ValidationErrorMalformed } // 判断过期 now := time.Now().Unix() if now > licence.Expires { return ValidationErrorExpired } // 判断机器码 mCode := GetMachineCode() if licence.RegCode.MachineCode != mCode { return ValidationErrorUnverifiableHost } return 0 }