成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

使用 Go 實現 License 認證

開發 后端
本篇文章將講解如何使用Go生成機器碼、創建License、驗證License及防止時間篡改,并提供完整可運行代碼示例,以讓您理解其中的邏輯。

在軟件授權管理中,License機制可以有效防止未授權使用,確保軟件的合法性。本篇文章將講解如何使用Go生成機器碼、創建License、驗證License及防止時間篡改,并提供完整可運行代碼示例,以讓您理解其中的邏輯。

License機制概述

在軟件授權體系中,License(許可證)是用于驗證軟件的合法使用權限的一種機制。常見License設計包含以下關鍵要素:

  • 機器碼:用于唯一標識設備,防止License盜用。
  • 到期時間:控制License的有效期,到期后軟件不可用。
  • 簽名校驗:使用HMAC-SHA256或者其他進行License簽名,防止篡改。
  • 防止篡改系統時間:存儲上次運行時間,防止用戶回退系統時間繞過License過期檢測。

實現思路

我們將實現如下功能:

(1) 生成機器碼:基于MAC地址 + CPU ID計算SHA256哈希,保證唯一性。

(2) 生成License:包含機器碼、過期時間、數字簽名,防止篡改。

(3) 存儲License:將License存入本地文件,在系統啟動時驗證。

(4) 校驗License:

  • 解析License并驗證簽名和過期時間。
  • 若License無效或過期,軟件拒絕運行。

(5) 防止篡改時間繞過License過期:本地存儲上次運行時間,若時間回退則拒絕運行。

代碼實現

生成機器碼:

package main


import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"net"
	"os/exec"
	"runtime"
	"strings"
)


// 獲取 MAC 地址
func getMacAddress() string {
	interfaces, err := net.Interfaces()
	if err != nil {
		return "unknown"
	}
	for _, iface := range interfaces {
		if len(iface.HardwareAddr) > 0 {
			return iface.HardwareAddr.String()
		}
	}
	return "unknown"
}


// 獲取 CPU ID
func getCpuID() string {
	var cmd *exec.Cmd
	switch runtime.GOOS {
	case "windows":
		cmd = exec.Command("wmic", "cpu", "get", "ProcessorId")
	case "linux":
		cmd = exec.Command("cat", "/proc/cpuinfo")
	case "darwin":
		cmd = exec.Command("sysctl", "-n", "machdep.cpu.brand_string")
	default:
		return "unknown"
	}
	output, err := cmd.Output()
	if err != nil {
		return "unknown"
	}
	return strings.TrimSpace(string(output))
}


// 生成機器碼
func generateMachineCode() string {
	data := getMacAddress() + getCpuID()
	hash := sha256.Sum256([]byte(data))
	return hex.EncodeToString(hash[:])
}

License結構:

package main


import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"time"
)


// License 結構
type License struct {
	MachineCode string `json:"machine_code"`
	ExpireAt    int64  `json:"expire_at"`
	Signature   string `json:"signature"`
}


var secretKey = "my-secret-key" // License 簽名密鑰


// 生成 License 簽名
func generateSignature(machineCode string, expireAt int64) string {
	data := fmt.Sprintf("%s:%d", machineCode, expireAt)
	h := hmac.New(sha256.New, []byte(secretKey))
	h.Write([]byte(data))
	return base64.StdEncoding.EncodeToString(h.Sum(nil))
}


// 生成 License
func generateLicense(machineCode string, days int) string {
	expireAt := time.Now().Add(time.Duration(days) * 24 * time.Hour).Unix()
	signature := generateSignature(machineCode, expireAt)


	license := License{
		MachineCode: machineCode,
		ExpireAt:    expireAt,
		Signature:   signature,
	}


	licenseBytes, _ := json.Marshal(license)
	return base64.StdEncoding.EncodeToString(licenseBytes)
}

存儲與讀取License:

// 存儲 License 到本地
func saveLicenseToFile(license string) error {
	return ioutil.WriteFile("license.txt", []byte(license), 0644)
}


// 讀取 License
func loadLicenseFromFile() (string, error) {
	data, err := ioutil.ReadFile("license.txt")
	if err != nil {
		return "", err
	}
	return string(data), nil
}

解析與驗證License:

// 解析 License
func parseLicense(encodedLicense string) (*License, error) {
	licenseBytes, err := base64.StdEncoding.DecodeString(encodedLicense)
	if err != nil {
		return nil, err
	}


	var license License
	if err := json.Unmarshal(licenseBytes, &license); err != nil {
		return nil, err
	}


	// 驗證簽名
	expectedSignature := generateSignature(license.MachineCode, license.ExpireAt)
	if license.Signature != expectedSignature {
		return nil, errors.New("invalid signature")
	}


	// 檢查是否過期
	if time.Now().Unix() > license.ExpireAt {
		return nil, errors.New("license expired")
	}


	return &license, nil
}

防止用戶回退系統時間:

// 記錄上次運行時間
type LastRun struct {
	Timestamp int64 `json:"timestamp"`
}


// 保存上次運行時間
func saveLastRunTime() error {
	data, _ := json.Marshal(LastRun{Timestamp: time.Now().Unix()})
	return ioutil.WriteFile("last_run.json", data, 0644)
}


// 讀取上次運行時間
func loadLastRunTime() (int64, error) {
	data, err := ioutil.ReadFile("last_run.json")
	if err != nil {
		return 0, err
	}


	var lastRun LastRun
	json.Unmarshal(data, &lastRun)
	return lastRun.Timestamp, nil
}


// 檢測系統時間是否被回退
func checkTimeValidity() bool {
	lastRun, err := loadLastRunTime()
	if err == nil && time.Now().Unix() < lastRun {
		return false // 系統時間被回退,拒絕啟動
	}
	saveLastRunTime()
	return true
}

啟動時驗證License:

func main() {
	machineCode := generateMachineCode()
	fmt.Println("Machine Code:", machineCode)


	// 讀取 License
	licenseStr, err := loadLicenseFromFile()
	if err != nil {
		fmt.Println("No valid license found. Generating a new one...")
		licenseStr = generateLicense(machineCode, 30) // 生成 30 天 License
		saveLicenseToFile(licenseStr)
	}


	// 驗證 License
	license, err := parseLicense(licenseStr)
	if err != nil {
		fmt.Println("License invalid:", err)
		fmt.Println("System exiting...")
		os.Exit(1)
	}


	fmt.Println(license)
	// 檢測是否篡改時間
	if !checkTimeValidity() {
		fmt.Println("System time tampered. Exiting...")
		os.Exit(1)
	}


	fmt.Println("License is valid. System running...")
}

運行結果如下所示:

Machine Code: 716372d3f7cd9d0c3cce2b9f08d3b8d133f98c2be8747cbc94ee76f9652a8fsa
No valid license found. Generating a new one...
&{716372d3f7cd9d0c3cce2b9f08d3b8d133f98c2be8747cbc94ee76f9652a8fsa 1260486000 McRH96QqLC0sXKnAS9v5Aw/RLnfVU2PAHq37jVLut4w=}
License is valid. System running...

總結

以上就是今天的所有內容,我們模擬式的實現了如下的功能:

  • 機器碼綁定設備
  •  License簽名防篡改
  •  License過期檢測
  • 防止用戶回退時間繞過授權

雖然是以模擬的方式實現的,但還是希望能夠在你實戰時提供一點思路和幫助。

責任編輯:趙寧寧 來源: 馬嘍編程筆記
相關推薦

2024-11-01 12:57:03

2021-06-21 11:25:54

GoTLS語言

2021-04-09 20:04:34

區塊鏈Go加密

2024-02-06 17:57:06

Go語言任務

2020-08-12 08:56:30

代碼凱撒密碼函數

2024-02-23 07:18:40

JWTWeb應用程序

2023-10-31 22:54:17

GoEventBus驅動編程

2023-04-18 08:27:16

日志級別日志包

2022-10-24 00:48:58

Go語言errgroup

2022-04-18 10:01:07

Go 語言漢諾塔游戲

2023-07-31 08:01:13

二叉搜索測試

2025-06-20 09:57:42

2022-05-16 10:58:12

Go 項目Makefilemake

2022-05-06 09:22:25

Go泛型

2023-10-23 20:03:02

Go緩存

2014-12-26 09:52:08

Go

2022-10-26 07:26:38

2024-12-25 14:03:03

2022-01-26 00:03:00

高可用gRPC微服務

2023-11-01 13:40:25

GolangGo
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 久久久久久亚洲精品 | 91精品国产综合久久久久久丝袜 | 中文字幕高清 | 亚洲福利 | 色av一区二区 | 毛片毛片毛片毛片 | 91精品国产91久久综合桃花 | 91麻豆产精品久久久久久 | 中文字幕不卡在线观看 | 伊人网国产 | 成人性生交大片免费看中文带字幕 | 成人av高清在线观看 | 日韩在线视频免费观看 | 在线播放中文字幕 | 国内精品视频在线 | 欧美www在线 | 欧美寡妇偷汉性猛交 | 亚洲性视频网站 | 国产精品入口久久 | 亚洲精品在线免费播放 | 久久久精品网站 | 亚洲欧美综合网 | 亚洲国产日韩欧美 | 日本理论片好看理论片 | 成人影音 | 99精品电影| 久久久久久久国产 | 久草免费在线视频 | 精品99在线 | 国产精品视频 | 美女张开腿露出尿口 | 亚洲精品在线免费看 | 激情毛片| 日韩av.com | 97av视频在线 | 欧美free性 | 亚洲 成人 在线 | 特a毛片| 亚州激情| 成人精品一区二区三区中文字幕 | 欧美精品成人一区二区三区四区 |