private static void Base64RoundTrip(string input, bool uriSafe) { byte[] data = Encoding.UTF8.GetBytes(input); string encoded = EncodingUtilities.ToBase64(data, uriSafe); byte[] output = EncodingUtilities.FromBase64(encoded); string actual = Encoding.UTF8.GetString(output); Assert.Equal(input, actual); }
/// <summary> /// Verifies that the signature header matches that of the actual body. /// </summary> protected virtual async Task VerifySignature(string id, HttpRequestMessage request) { string secretKey = await GetReceiverConfig(request, Name, id, SecretMinLength, SecretMaxLength); // Get the expected hash from the signature header string header = GetRequestHeader(request, SignatureHeaderName); string[] values = header.SplitAndTrim('='); if (values.Length != 2 || !string.Equals(values[0], SignatureHeaderKey, StringComparison.OrdinalIgnoreCase)) { string msg = string.Format(CultureInfo.CurrentCulture, TwitterReceiverResources.Receiver_BadHeaderValue, SignatureHeaderName, SignatureHeaderKey, "<value>"); request.GetConfiguration().DependencyResolver.GetLogger().Error(msg); HttpResponseMessage invalidHeader = request.CreateErrorResponse(HttpStatusCode.BadRequest, msg); throw new HttpResponseException(invalidHeader); } byte[] expectedHash; try { expectedHash = EncodingUtilities.FromBase64(values[1]); } catch (Exception ex) { string msg = string.Format(CultureInfo.CurrentCulture, TwitterReceiverResources.Receiver_BadHeaderEncoding, SignatureHeaderName); request.GetConfiguration().DependencyResolver.GetLogger().Error(msg, ex); HttpResponseMessage invalidEncoding = request.CreateErrorResponse(HttpStatusCode.BadRequest, msg); throw new HttpResponseException(invalidEncoding); } // Get the actual hash of the request body byte[] actualHash; byte[] secret = Encoding.UTF8.GetBytes(secretKey); using (var hasher = new HMACSHA256(secret)) { byte[] data = await request.Content.ReadAsByteArrayAsync(); actualHash = hasher.ComputeHash(data); } // Now verify that the provided hash matches the expected hash. if (!SecretEqual(expectedHash, actualHash)) { var badSignature = CreateBadSignatureResponse(request, SignatureHeaderName); throw new HttpResponseException(badSignature); } }