identity.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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":
  34. case "p384":
  35. idType = zerotier.IdentityTypeP384
  36. default:
  37. Help()
  38. os.Exit(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. os.Exit(1)
  45. }
  46. fmt.Println(id.PrivateKeyString())
  47. os.Exit(0)
  48. case "getpublic":
  49. if len(args) == 2 {
  50. fmt.Println(readIdentity(args[1]).String())
  51. os.Exit(0)
  52. }
  53. case "validate":
  54. if len(args) == 2 {
  55. if readIdentity(args[1]).LocallyValidate() {
  56. fmt.Println("OK")
  57. os.Exit(0)
  58. }
  59. fmt.Println("FAILED")
  60. os.Exit(1)
  61. }
  62. case "sign", "verify":
  63. if len(args) > 2 {
  64. id := readIdentity(args[1])
  65. msg, err := ioutil.ReadFile(args[2])
  66. if err != nil {
  67. fmt.Printf("ERROR: unable to read input file: %s\n", err.Error())
  68. os.Exit(1)
  69. }
  70. if args[0] == "verify" {
  71. if len(args) == 4 {
  72. sig, err := hex.DecodeString(strings.TrimSpace(args[3]))
  73. if err != nil {
  74. fmt.Println("FAILED")
  75. os.Exit(1)
  76. }
  77. if id.Verify(msg, sig) {
  78. fmt.Println("OK")
  79. os.Exit(0)
  80. }
  81. }
  82. fmt.Println("FAILED")
  83. os.Exit(1)
  84. } else {
  85. sig, err := id.Sign(msg)
  86. if err != nil {
  87. fmt.Printf("ERROR: internal error signing message: %s\n", err.Error())
  88. os.Exit(1)
  89. }
  90. fmt.Println(hex.EncodeToString(sig))
  91. os.Exit(0)
  92. }
  93. }
  94. }
  95. }
  96. Help()
  97. os.Exit(1)
  98. }