From 3163811279a9d074a8d33bbf6ae4b6f776c0c46d Mon Sep 17 00:00:00 2001 From: Matthew Endsley Date: Wed, 13 Jan 2021 00:18:45 -0800 Subject: [PATCH] Add the psuedoranomm function P_SHA256 --- Hazel/Dtls/PrfSha256.cs | 56 +++++++++++++++++++++++++++++++++++++++++ Hazel/Hazel.csproj | 1 + 2 files changed, 57 insertions(+) create mode 100644 Hazel/Dtls/PrfSha256.cs diff --git a/Hazel/Dtls/PrfSha256.cs b/Hazel/Dtls/PrfSha256.cs new file mode 100644 index 0000000..683e55f --- /dev/null +++ b/Hazel/Dtls/PrfSha256.cs @@ -0,0 +1,56 @@ +using System.Text; +using System.Security.Cryptography; + +namespace Hazel.Dtls +{ + /// + /// The P_SHA256 Psuedorandom Function + /// + public struct PrfSha256 + { + /// + /// Expand a secret key + /// + /// Output span. Length determines how much data to generate + /// Original key to expand + /// Label (treated as a salt) + /// Seed for expansion (treated as a salt) + public static void ExpandSecret(ByteSpan output, ByteSpan key, string label, ByteSpan initialSeed) + { + ByteSpan writer = output; + + ///TODO(mendsley): Look into pre-calculating all of these + ByteSpan labelAsBytes = Encoding.ASCII.GetBytes(label); + + byte[] roundSeed = new byte[labelAsBytes.Length + initialSeed.Length]; + labelAsBytes.CopyTo(roundSeed); + initialSeed.CopyTo(roundSeed, labelAsBytes.Length)); + + byte[] hashA = roundSeed; + + using (HMACSHA256 hmac = new HMACSHA256(key.ToArray())) + { + byte[] input = new byte[hmac.OutputBlockSize + roundSeed.Length]; + new ByteSpan(roundSeed).CopyTo(input, hmac.OutputBlockSize); + + while (writer.Length > 0) + { + // Update hashA + hashA = hmac.ComputeHash(hashA); + + // generate hash input + new ByteSpan(hashA).CopyTo(input); + + ByteSpan roundOutput = hmac.ComputeHash(input); + if (roundOutput.Length > writer.Length) + { + roundOutput = roundOutput.Slice(0, writer.Length); + } + + roundOutput.CopyTo(writer); + writer = writer.Slice(roundOutput.Length); + } + } + } + } +} diff --git a/Hazel/Hazel.csproj b/Hazel/Hazel.csproj index 1f130f7..e75bb1e 100644 --- a/Hazel/Hazel.csproj +++ b/Hazel/Hazel.csproj @@ -80,6 +80,7 @@ + -- 2.39.5