From: Matthew Endsley Date: Wed, 13 Jan 2021 09:30:55 +0000 (-0800) Subject: Add record wire format conversions X-Git-Tag: 1.0.0~20^2~25^2 X-Git-Url: https://git.deb.at/?a=commitdiff_plain;h=113c1215a368590f649b3b3ba9d10f342b63de90;p=rhonda%2Fimpostor.hazel.git Add record wire format conversions --- diff --git a/Hazel/Dtls/Record.cs b/Hazel/Dtls/Record.cs new file mode 100644 index 0000000..affb8a6 --- /dev/null +++ b/Hazel/Dtls/Record.cs @@ -0,0 +1,76 @@ +namespace Hazel.Dtls +{ + /// + /// DTLS version constants + /// + public enum ProtocolVersion : ushort + { + /// + /// DTLS 1.2 + /// + DTLS1_2 = 0xFEFD, + } + + /// + /// DTLS record content type + /// + public enum ContentType : byte + { + ChangeCipherSpec = 20, + Alert = 21, + Handshake = 22, + ApplicationData = 23, + } + + /// + /// Encode/decode DTLS record header + /// + public struct Record + { + public ContentType ContentType; + public ushort Epoch; + public ulong SequenceNumber; + public ushort Length; + + public const int Size = 13; + + /// + /// Parse a DTLS record from wire format + /// + /// True if we successfully parse the record header. Otherwise false + public static bool Parse(out Record record, ByteSpan span) + { + record = new Record(); + + if (span.Length < Size) + { + return false; + } + + record.ContentType = (ContentType)span[0]; + ProtocolVersion version = (ProtocolVersion)span.ReadBigEndian16(1); + record.Epoch = span.ReadBigEndian16(3); + record.SequenceNumber = span.ReadBigEndian48(5); + record.Length = span.ReadBigEndian16(11); + + if (version != ProtocolVersion.DTLS1_2) + { + return false; + } + + return true; + } + + /// + /// Encode a DTLS record to wire format + /// + public void Encode(ByteSpan span) + { + span[0] = (byte)this.ContentType; + span.WriteBigEndian16((ushort)ProtocolVersion.DTLS1_2); + span.WriteBigEndian16(this.Epoch, 3); + span.WriteBigEndian48(this.SequenceNumber, 5); + span.WriteBigEndian16(this.Length, 11); + } + } +} diff --git a/Hazel/Hazel.csproj b/Hazel/Hazel.csproj index e75bb1e..e102524 100644 --- a/Hazel/Hazel.csproj +++ b/Hazel/Hazel.csproj @@ -81,6 +81,7 @@ +