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