summaryrefslogtreecommitdiff
path: root/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/random.go
blob: 0ade936eb9bf07ec68dd13670b2f644166cbe77e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package handshake

import (
	"crypto/rand"
	"encoding/binary"
	"time"
)

// Consts for Random in Handshake
const (
	RandomBytesLength = 28
	RandomLength      = RandomBytesLength + 4
)

// Random value that is used in ClientHello and ServerHello
//
// https://tools.ietf.org/html/rfc4346#section-7.4.1.2
type Random struct {
	GMTUnixTime time.Time
	RandomBytes [RandomBytesLength]byte
}

// MarshalFixed encodes the Handshake
func (r *Random) MarshalFixed() [RandomLength]byte {
	var out [RandomLength]byte

	binary.BigEndian.PutUint32(out[0:], uint32(r.GMTUnixTime.Unix()))
	copy(out[4:], r.RandomBytes[:])

	return out
}

// UnmarshalFixed populates the message from encoded data
func (r *Random) UnmarshalFixed(data [RandomLength]byte) {
	r.GMTUnixTime = time.Unix(int64(binary.BigEndian.Uint32(data[0:])), 0)
	copy(r.RandomBytes[:], data[4:])
}

// Populate fills the handshakeRandom with random values
// may be called multiple times
func (r *Random) Populate() error {
	r.GMTUnixTime = time.Now()

	tmp := make([]byte, RandomBytesLength)
	_, err := rand.Read(tmp)
	copy(r.RandomBytes[:], tmp)

	return err
}