mac-cpu.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package api
  2. import (
  3. "box-cost/conf"
  4. "crypto/hmac"
  5. "crypto/sha256"
  6. "fmt"
  7. "net/http"
  8. "time"
  9. "github.com/gin-gonic/gin"
  10. "github.com/shirou/gopsutil/net"
  11. )
  12. func Mac(r *GinRouter) {
  13. r.GET("/mac/info", MacInfo)
  14. r.POST("/get/code", GetCode)
  15. }
  16. type DeviceInfo struct {
  17. DeviceId string
  18. CreateTime time.Time
  19. AppName string
  20. AppVersion string
  21. }
  22. const SECRET_KEY = "DFDFEXVEG"
  23. func MacInfo(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  24. fmt.Println(conf.AppConfig.Name)
  25. interfaces, err := net.Interfaces()
  26. if err != nil {
  27. return nil, err
  28. }
  29. macAddr := getRealMacAddr(interfaces)
  30. deviceInfo := &DeviceInfo{
  31. DeviceId: UtilMd5(macAddr),
  32. AppName: "Toolchain",
  33. AppVersion: "v1.0.0",
  34. CreateTime: time.Now(),
  35. }
  36. return deviceInfo, nil
  37. }
  38. func GetCode(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  39. deviceId := c.Query("deviceId")
  40. if len(deviceId) < 1 {
  41. fmt.Println("deviceId 为空")
  42. c.String(http.StatusOK, "err")
  43. return nil, nil
  44. }
  45. key := []byte(SECRET_KEY)
  46. message := []byte(deviceId) // 待签名的消息
  47. // 创建一个 HMAC-SHA256 实例
  48. h := hmac.New(sha256.New, key)
  49. // 写入消息
  50. h.Write(message)
  51. // 计算签名
  52. signature := h.Sum(nil)
  53. fmt.Printf("%x\n", signature)
  54. // fmt.Println(len("86068c837d554c8aba4f997b51be6bc209b68cdad7c5a4a0adccbfc289adf4a2"))
  55. // fmt.Println(len("63e208dc7452ab74932b9e37"))
  56. // fmt.Println(len(UtilMd5(mac)))
  57. // 输出签名结果
  58. c.String(http.StatusOK, fmt.Sprintf("%x", signature))
  59. return nil, nil
  60. }
  61. // b0:6e:bf:c5:32:30
  62. func getRealMacAddr(netInterfaces []net.InterfaceStat) string {
  63. loindex := 0
  64. for _, netInterface := range netInterfaces {
  65. if netInterface.Name == "lo" {
  66. loindex = netInterface.Index
  67. break
  68. }
  69. }
  70. if len(netInterfaces) < loindex+1 {
  71. return ""
  72. }
  73. return netInterfaces[loindex].HardwareAddr
  74. }