package api import ( "box-cost/conf" "box-cost/db/repo" "box-cost/log" "crypto/hmac" "crypto/sha256" "fmt" "net/http" "time" "github.com/gin-gonic/gin" "github.com/shirou/gopsutil/net" "go.mongodb.org/mongo-driver/bson/primitive" ) func Mac(r *GinRouter) { r.GET("/mac/info", MacInfo) r.POST("/get/code", GetCode) } type DeviceInfo struct { DeviceId string CreateTime time.Time AppName string AppVersion string } const SECRET_KEY = "DFDFEXVEG" func MacInfo(c *gin.Context, apictx *ApiSession) (interface{}, error) { fmt.Println(conf.AppConfig.Name) interfaces, err := net.Interfaces() if err != nil { return nil, err } macAddr := getRealMacAddr(interfaces) deviceInfo := &DeviceInfo{ DeviceId: UtilMd5(macAddr), AppName: "Toolchain", AppVersion: "v1.0.0", CreateTime: time.Now(), } return deviceInfo, nil } func GetCode(c *gin.Context, apictx *ApiSession) (interface{}, error) { deviceId := c.Query("deviceId") if len(deviceId) < 1 { fmt.Println("deviceId 为空") c.String(http.StatusOK, "err") return nil, nil } key := []byte(SECRET_KEY) message := []byte(deviceId) // 待签名的消息 // 创建一个 HMAC-SHA256 实例 h := hmac.New(sha256.New, key) // 写入消息 h.Write(message) // 计算签名 signature := h.Sum(nil) fmt.Printf("%x\n", signature) // fmt.Println(len("86068c837d554c8aba4f997b51be6bc209b68cdad7c5a4a0adccbfc289adf4a2")) // fmt.Println(len("63e208dc7452ab74932b9e37")) // fmt.Println(len(UtilMd5(mac))) appName := c.Query("appName") appVersion := c.Query("appVersion") // create_time := c.Query("createTime") // deviceId设置唯一key type RegCode struct { Id primitive.ObjectID `bson:"_id,omitempty" json:"_id"` AppName string `bson:"appName,omitempty" json:"appName"` AppVersion string `bson:"appVersion,omitempty" json:"appVersion"` DeviceId string `bson:"deviceId,omitempty" json:"deviceId"` Key string `bson:"key,omitempty" json:"key"` Code string `bson:"code,omitempty" json:"code"` CreateTime time.Time `bson:"createTime,omitempty" json:"createTime"` UpdateTIme time.Time `bson:"updateTIme,omitempty" json:"updateTIme"` ExpireTime time.Time `bson:"expireTime,omitempty" json:"expireTime"` Status int `bson:"status,omitempty" json:"status"` } _, err := repo.RepoAddDoc(apictx.CreateRepoCtx(), "reg-code", &RegCode{ AppName: appName, AppVersion: appVersion, DeviceId: deviceId, Key: SECRET_KEY, Code: fmt.Sprintf("%x", signature), CreateTime: time.Now(), UpdateTIme: time.Now(), ExpireTime: time.Now().AddDate(0, 0, 3), Status: 1, }) if err != nil { log.Error(err) return nil, err } // 输出签名结果 c.String(http.StatusOK, fmt.Sprintf("%x", signature)) return nil, nil } // b0:6e:bf:c5:32:30 func getRealMacAddr(netInterfaces []net.InterfaceStat) string { loindex := 0 for _, netInterface := range netInterfaces { if netInterface.Name == "lo" { loindex = netInterface.Index break } } if len(netInterfaces) < loindex+1 { return "" } return netInterfaces[loindex].HardwareAddr }