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: 2024-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. "os"
  19. "strings"
  20. "zerotier/pkg/zerotier"
  21. )
  22. func Identity(args []string) {
  23. if len(args) > 0 {
  24. switch args[0] {
  25. case "new":
  26. idType := zerotier.IdentityTypeC25519
  27. if len(args) > 1 {
  28. if len(args) > 2 {
  29. Help()
  30. os.Exit(1)
  31. }
  32. switch args[1] {
  33. case "c25519", "C25519", "0":
  34. idType = zerotier.IdentityTypeC25519
  35. case "p384", "P384", "1":
  36. idType = zerotier.IdentityTypeP384
  37. default:
  38. Help()
  39. os.Exit(1)
  40. }
  41. }
  42. id, err := zerotier.NewIdentity(idType)
  43. if err != nil {
  44. fmt.Printf("ERROR: internal error generating identity: %s\n", err.Error())
  45. os.Exit(1)
  46. }
  47. fmt.Println(id.PrivateKeyString())
  48. os.Exit(0)
  49. case "getpublic":
  50. if len(args) == 2 {
  51. fmt.Println(readIdentity(args[1]).String())
  52. os.Exit(0)
  53. }
  54. case "fingerprint":
  55. if len(args) == 2 {
  56. fmt.Println(readIdentity(args[1]).Fingerprint().String())
  57. os.Exit(0)
  58. }
  59. case "validate":
  60. if len(args) == 2 {
  61. if readIdentity(args[1]).LocallyValidate() {
  62. fmt.Println("OK")
  63. os.Exit(0)
  64. }
  65. fmt.Println("FAILED")
  66. os.Exit(1)
  67. }
  68. case "sign", "verify":
  69. if len(args) > 2 {
  70. id := readIdentity(args[1])
  71. msg, err := ioutil.ReadFile(args[2])
  72. if err != nil {
  73. fmt.Printf("ERROR: unable to read input file: %s\n", err.Error())
  74. os.Exit(1)
  75. }
  76. if args[0] == "verify" {
  77. if len(args) == 4 {
  78. sig, err := hex.DecodeString(strings.TrimSpace(args[3]))
  79. if err != nil {
  80. fmt.Println("FAILED")
  81. os.Exit(1)
  82. }
  83. if id.Verify(msg, sig) {
  84. fmt.Println("OK")
  85. os.Exit(0)
  86. }
  87. }
  88. fmt.Println("FAILED")
  89. os.Exit(1)
  90. } else {
  91. sig, err := id.Sign(msg)
  92. if err != nil {
  93. fmt.Printf("ERROR: internal error signing message: %s\n", err.Error())
  94. os.Exit(1)
  95. }
  96. fmt.Println(hex.EncodeToString(sig))
  97. os.Exit(0)
  98. }
  99. }
  100. }
  101. }
  102. Help()
  103. os.Exit(1)
  104. }