random.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. package handshake
  4. import (
  5. "crypto/rand"
  6. "encoding/binary"
  7. "time"
  8. )
  9. // Consts for Random in Handshake
  10. const (
  11. RandomBytesLength = 28
  12. RandomLength = RandomBytesLength + 4
  13. )
  14. // Random value that is used in ClientHello and ServerHello
  15. //
  16. // https://tools.ietf.org/html/rfc4346#section-7.4.1.2
  17. type Random struct {
  18. GMTUnixTime time.Time
  19. RandomBytes [RandomBytesLength]byte
  20. }
  21. // MarshalFixed encodes the Handshake
  22. func (r *Random) MarshalFixed() [RandomLength]byte {
  23. var out [RandomLength]byte
  24. binary.BigEndian.PutUint32(out[0:], uint32(r.GMTUnixTime.Unix()))
  25. copy(out[4:], r.RandomBytes[:])
  26. return out
  27. }
  28. // UnmarshalFixed populates the message from encoded data
  29. func (r *Random) UnmarshalFixed(data [RandomLength]byte) {
  30. r.GMTUnixTime = time.Unix(int64(binary.BigEndian.Uint32(data[0:])), 0)
  31. copy(r.RandomBytes[:], data[4:])
  32. }
  33. // Populate fills the handshakeRandom with random values
  34. // may be called multiple times
  35. func (r *Random) Populate() error {
  36. r.GMTUnixTime = time.Now()
  37. tmp := make([]byte, RandomBytesLength)
  38. _, err := rand.Read(tmp)
  39. copy(r.RandomBytes[:], tmp)
  40. return err
  41. }