public void ToHex_FromHex_Roundtrips_UriSafe(string input) { byte[] data = Encoding.UTF8.GetBytes(input); string encoded = EncodingUtilities.ToHex(data); byte[] output = EncodingUtilities.FromHex(encoded); string actual = Encoding.UTF8.GetString(output); Assert.Equal(input, actual); }
public void ToHex_ConvertsCorrectly(string input) { // Arrange byte[] bytes = Encoding.UTF8.GetBytes(input); string expected = ToExpectedHex(bytes); // Act string actual = EncodingUtilities.ToHex(bytes); // Assert Assert.Equal(expected, actual); }
protected virtual void SignWebHookRequest(WebHookWorkItem workItem, HttpRequestMessage request, JObject body) { if (workItem == null) { throw new ArgumentNullException(nameof(workItem)); } if (workItem.WebHook == null) { string msg = "WebHook"; throw new ArgumentException(msg, "workItem"); } if (request == null) { throw new ArgumentNullException(nameof(request)); } if (body == null) { throw new ArgumentNullException(nameof(body)); } byte[] secret = Encoding.UTF8.GetBytes(workItem.WebHook.Secret); using (var hasher = new HMACSHA256(secret)) { string serializedBody = body.ToString(); request.Content = new StringContent(serializedBody, Encoding.UTF8, "application/json"); byte[] data = Encoding.UTF8.GetBytes(serializedBody); byte[] sha256 = hasher.ComputeHash(data); string headerValue = string.Format(CultureInfo.InvariantCulture, SignatureHeaderValueTemplate, EncodingUtilities.ToHex(sha256)); request.Headers.Add(SignatureHeaderName, headerValue); } }
/// <summary> /// Adds a SHA 256 signature to the <paramref name="body"/> and adds it to the <paramref name="request"/> as an /// HTTP header to the <see cref="HttpRequestMessage"/> along with the entity body. /// </summary> /// <param name="workItem">The current <see cref="WebHookWorkItem"/>.</param> /// <param name="request">The request to add the signature to.</param> /// <param name="body">The body to sign and add to the request.</param> protected virtual void SignWebHookRequest(WebHookWorkItem workItem, HttpRequestMessage request, Stream body) { if (workItem == null) { throw new ArgumentNullException(nameof(workItem)); } if (workItem.WebHook == null) { var message = string.Format(CultureInfo.CurrentCulture, CustomResources.Sender_BadWorkItem, GetType().Name, "WebHook"); throw new ArgumentException(message, "workItem"); } if (request == null) { throw new ArgumentNullException(nameof(request)); } if (body == null) { throw new ArgumentNullException(nameof(body)); } var secret = Encoding.UTF8.GetBytes(workItem.WebHook.Secret); using var hasher = new HMACSHA256(secret); var sha256 = hasher.ComputeHash(body); var headerValue = string.Format(CultureInfo.InvariantCulture, SignatureHeaderValueTemplate, EncodingUtilities.ToHex(sha256)); request.Headers.Add(SignatureHeaderName, headerValue); body.Seek(0, SeekOrigin.Begin); var content = new StreamContent(body); content.Headers.ContentType = ApplicationJson; request.Content = content; }