keys.go 995 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package aerotun
  2. import (
  3. "encoding/base64"
  4. "encoding/hex"
  5. "errors"
  6. "github.com/flynn/noise"
  7. )
  8. func decodeKey(s string) ([]byte, error) {
  9. if len(s) == 64 {
  10. if b, err := hex.DecodeString(s); err == nil {
  11. return b, nil
  12. }
  13. }
  14. b, err := base64.StdEncoding.DecodeString(s)
  15. if err != nil || len(b) != 32 {
  16. return nil, errors.New("key must encode exactly 32 bytes (64 hex characters or base64)")
  17. }
  18. return b, nil
  19. }
  20. func GenerateIdentity() (private, public string, err error) {
  21. k, err := noise.DH25519.GenerateKeypair(nil)
  22. if err != nil {
  23. return "", "", err
  24. }
  25. return base64.StdEncoding.EncodeToString(k.Private), base64.StdEncoding.EncodeToString(k.Public), nil
  26. }
  27. // PublicView is the only configuration representation sent to API clients.
  28. // Secret fields remain available solely for private configuration persistence.
  29. func (c TunnelInstance) PublicView() TunnelInstance {
  30. c.HasPSK = c.PSK != ""
  31. c.PSK = ""
  32. c.HasPrivateKey = c.PrivateKey != ""
  33. c.PrivateKey = ""
  34. return c
  35. }