// TODO: This is ugly af , maybe an Action<request,header> instead ? // <summary> // Create IRestRequest object with required headers for CheckoutFinland API // </summary> private IRestRequest CreateRequest(string url, Method method, object requestBody, IDictionary <string, string> extraHeader = null) { IRestRequest request = new RestRequest(url, method, DataFormat.Json); IDictionary <string, string> headerDictionary = new Dictionary <string, string>() { { CheckoutRequestHeaders.Method, method.ToString("g") }, { CheckoutRequestHeaders.NOnce, Guid.NewGuid().ToString() }, { CheckoutRequestHeaders.Timestamp, DateTimeOffset.UtcNow.ToIsoDateTimeString() } }; // TODO: If extra header already there , wut wut ? if (extraHeader != null) { extraHeader.ToList().Each(kv => { headerDictionary.Add(kv.Key, kv.Value); }); } headerDictionary.ToList().Each(kv => { request.AddHeader(kv.Key, kv.Value); }); var toEncrypt = EncryptionUtils.ConvertCustomRequestHeaders( defaultHeaders.Concat(headerDictionary).ToDictionary(x => x.Key, x => x.Value) ); var signature = EncryptionUtils.CalculateHmac(_secretKey, toEncrypt.ToList(), SerializationUtils.RequestBodyToString(requestBody)); request.AddHeader(CheckoutRequestHeaders.Signature, signature); if (requestBody != null) { request.AddJsonBody(requestBody); } return(request); }
// Quite dependent on JsonNet and RestSharp.. private bool TryGetValidatedResponse <T>(IRestResponse restResponse, out T responseData) where T : class, new() { // Validate response var responseDictionary = EncryptionUtils.ConvertCustomRequestHeaders(restResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString())); var encryptedSignature = EncryptionUtils.CalculateHmac(_secretKey, responseDictionary, restResponse.Content); var responseSignature = restResponse.Headers.SingleOrDefault(x => x.Name.Equals(CheckoutRequestHeaders.Signature))?.Value.ToString(); if (encryptedSignature == responseSignature) { responseData = JsonConvert.DeserializeObject <T>(restResponse.Content, JsonNetSerializer.SerializerSettings); return(true); } responseData = null; return(false); }
public void CanEncryptWithEmptyBody() { const string expected = "9ebf9b5ea57b6cbb26ffe539a0c52681e52f2c86e24c606ba042d972168b0dba"; IDictionary <string, string> headersDictionary = new Dictionary <string, string>() { { CheckoutRequestHeaders.Account, "375917" }, { CheckoutRequestHeaders.Algorithm, "sha256" }, { CheckoutRequestHeaders.Method, "GET" }, { CheckoutRequestHeaders.NOnce, "564635208570151" }, { CheckoutRequestHeaders.Timestamp, "2018-07-06T10:01:31.904Z" } }; var secretKey = "SAIPPUAKAUPPIAS"; var jsonBody = string.Empty; var encryptedString = EncryptionUtils.CalculateHmac(secretKey, headersDictionary, jsonBody); var anotherEncryptedString = EncryptionUtils.CalculateHmac(secretKey, EncryptionUtils.ConvertCustomRequestHeaders(headersDictionary), jsonBody); encryptedString.Should().BeEquivalentTo(expected); anotherEncryptedString.Should().BeEquivalentTo(expected); }