x25519.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package all
  2. import (
  3. "crypto/rand"
  4. "encoding/base64"
  5. "fmt"
  6. "github.com/xtls/xray-core/main/commands/base"
  7. "golang.org/x/crypto/curve25519"
  8. )
  9. var cmdX25519 = &base.Command{
  10. UsageLine: `{{.Exec}} x25519 [-i "private key (base64.RawURLEncoding)"]`,
  11. Short: `Generate key pair for x25519 key exchange`,
  12. Long: `
  13. Generate key pair for x25519 key exchange.
  14. Random: {{.Exec}} x25519
  15. From private key: {{.Exec}} x25519 -i "private key (base64.RawURLEncoding)"
  16. `,
  17. }
  18. func init() {
  19. cmdX25519.Run = executeX25519 // break init loop
  20. }
  21. var input_base64 = cmdX25519.Flag.String("i", "", "")
  22. func executeX25519(cmd *base.Command, args []string) {
  23. var output string
  24. var err error
  25. var privateKey []byte
  26. var publicKey []byte
  27. if len(*input_base64) > 0 {
  28. privateKey, err = base64.RawURLEncoding.DecodeString(*input_base64)
  29. if err != nil {
  30. output = err.Error()
  31. goto out
  32. }
  33. if len(privateKey) != curve25519.ScalarSize {
  34. output = "Invalid length of private key."
  35. goto out
  36. }
  37. }
  38. if privateKey == nil {
  39. privateKey = make([]byte, curve25519.ScalarSize)
  40. if _, err = rand.Read(privateKey); err != nil {
  41. output = err.Error()
  42. goto out
  43. }
  44. }
  45. // Modify random bytes using algorithm described at:
  46. // https://cr.yp.to/ecdh.html.
  47. privateKey[0] &= 248
  48. privateKey[31] &= 127
  49. privateKey[31] |= 64
  50. if publicKey, err = curve25519.X25519(privateKey, curve25519.Basepoint); err != nil {
  51. output = err.Error()
  52. goto out
  53. }
  54. output = fmt.Sprintf("Private key: %v\nPublic key: %v",
  55. base64.RawURLEncoding.EncodeToString(privateKey),
  56. base64.RawURLEncoding.EncodeToString(publicKey))
  57. out:
  58. fmt.Println(output)
  59. }