rand.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. package ice
  4. import "github.com/pion/randutil"
  5. const (
  6. runesAlpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  7. runesDigit = "0123456789"
  8. runesCandidateIDFoundation = runesAlpha + runesDigit + "+/"
  9. lenUFrag = 16
  10. lenPwd = 32
  11. )
  12. // Seeding random generator each time limits number of generated sequence to 31-bits,
  13. // and causes collision on low time accuracy environments.
  14. // Use global random generator seeded by crypto grade random.
  15. var (
  16. globalMathRandomGenerator = randutil.NewMathRandomGenerator() //nolint:gochecknoglobals
  17. globalCandidateIDGenerator = candidateIDGenerator{globalMathRandomGenerator} //nolint:gochecknoglobals
  18. )
  19. // candidateIDGenerator is a random candidate ID generator.
  20. // Candidate ID is used in SDP and always shared to the other peer.
  21. // It doesn't require cryptographic random.
  22. type candidateIDGenerator struct {
  23. randutil.MathRandomGenerator
  24. }
  25. func newCandidateIDGenerator() *candidateIDGenerator {
  26. return &candidateIDGenerator{
  27. randutil.NewMathRandomGenerator(),
  28. }
  29. }
  30. func (g *candidateIDGenerator) Generate() string {
  31. // https://tools.ietf.org/html/rfc5245#section-15.1
  32. // candidate-id = "candidate" ":" foundation
  33. // foundation = 1*32ice-char
  34. // ice-char = ALPHA / DIGIT / "+" / "/"
  35. return "candidate:" + g.MathRandomGenerator.GenerateString(32, runesCandidateIDFoundation)
  36. }
  37. // generatePwd generates ICE pwd.
  38. // This internally uses generateCryptoRandomString.
  39. func generatePwd() (string, error) {
  40. return randutil.GenerateCryptoRandomString(lenPwd, runesAlpha)
  41. }
  42. // generateUFrag generates ICE user fragment.
  43. // This internally uses generateCryptoRandomString.
  44. func generateUFrag() (string, error) {
  45. return randutil.GenerateCryptoRandomString(lenUFrag, runesAlpha)
  46. }