curves.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package ciphers
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/pion/dtls/v3/pkg/crypto/elliptic"
  6. )
  7. type CurveList = []elliptic.Curve
  8. var FullCurveList = CurveList{
  9. elliptic.X25519,
  10. elliptic.P256,
  11. elliptic.P384,
  12. }
  13. var DefaultCurveList = FullCurveList
  14. var DefaultCurveListString = CurveListToString(DefaultCurveList)
  15. var CurveNameToID map[string]elliptic.Curve
  16. func init() {
  17. CurveNameToID = make(map[string]elliptic.Curve)
  18. for _, curve := range FullCurveList {
  19. CurveNameToID[curve.String()] = curve
  20. }
  21. }
  22. func CurveIDToString(curve elliptic.Curve) string {
  23. return curve.String()
  24. }
  25. func CurveListToString(lst CurveList) string {
  26. var b strings.Builder
  27. var firstPrinted bool
  28. for _, curve := range lst {
  29. if firstPrinted {
  30. b.WriteByte(':')
  31. } else {
  32. firstPrinted = true
  33. }
  34. b.WriteString(curve.String())
  35. }
  36. return b.String()
  37. }
  38. func StringToCurveList(str string) (CurveList, error) {
  39. if str == "" {
  40. return CurveList{}, nil
  41. }
  42. parts := strings.Split(str, ":")
  43. var res CurveList
  44. for _, name := range parts {
  45. if id, ok := CurveNameToID[name]; ok {
  46. res = append(res, id)
  47. } else {
  48. return nil, fmt.Errorf("unknown curve: %q", name)
  49. }
  50. }
  51. return res, nil
  52. }