identity.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2025-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. package cli
  14. import (
  15. "encoding/hex"
  16. "fmt"
  17. "io/ioutil"
  18. "strings"
  19. "zerotier/pkg/zerotier"
  20. )
  21. func Identity(args []string) int {
  22. if len(args) > 0 {
  23. switch args[0] {
  24. case "new":
  25. idType := zerotier.IdentityTypeC25519
  26. if len(args) > 1 {
  27. if len(args) > 2 {
  28. Help()
  29. return 1
  30. }
  31. switch args[1] {
  32. case "c25519", "C25519", "0":
  33. idType = zerotier.IdentityTypeC25519
  34. case "p384", "P384", "1":
  35. idType = zerotier.IdentityTypeP384
  36. default:
  37. Help()
  38. return 1
  39. }
  40. }
  41. id, err := zerotier.NewIdentity(idType)
  42. if err != nil {
  43. fmt.Printf("ERROR: internal error generating identity: %s\n", err.Error())
  44. return 1
  45. }
  46. fmt.Println(id.PrivateKeyString())
  47. return 0
  48. case "getpublic":
  49. if len(args) == 2 {
  50. fmt.Println(readIdentity(args[1]).String())
  51. return 0
  52. }
  53. case "fingerprint":
  54. if len(args) == 2 {
  55. fmt.Println(readIdentity(args[1]).Fingerprint().String())
  56. return 0
  57. }
  58. case "validate":
  59. if len(args) == 2 {
  60. if readIdentity(args[1]).LocallyValidate() {
  61. fmt.Println("OK")
  62. return 0
  63. }
  64. fmt.Println("FAILED")
  65. return 1
  66. }
  67. case "sign", "verify":
  68. if len(args) > 2 {
  69. id := readIdentity(args[1])
  70. msg, err := ioutil.ReadFile(args[2])
  71. if err != nil {
  72. fmt.Printf("ERROR: unable to read input file: %s\n", err.Error())
  73. return 1
  74. }
  75. if args[0] == "verify" {
  76. if len(args) == 4 {
  77. sig, err := hex.DecodeString(strings.TrimSpace(args[3]))
  78. if err != nil {
  79. fmt.Println("FAILED")
  80. return 1
  81. }
  82. if id.Verify(msg, sig) {
  83. fmt.Println("OK")
  84. return 0
  85. }
  86. }
  87. fmt.Println("FAILED")
  88. return 1
  89. } else {
  90. sig, err := id.Sign(msg)
  91. if err != nil {
  92. fmt.Printf("ERROR: internal error signing message: %s\n", err.Error())
  93. return 1
  94. }
  95. fmt.Println(hex.EncodeToString(sig))
  96. return 0
  97. }
  98. }
  99. }
  100. }
  101. Help()
  102. return 1
  103. }