Saturday, April 2, 2016

Setting Up API Request with HMAC SHA256 hashing

// Set up request
            var publicKey = "123";
            var privateKey = "123";
            var domain = "portal.example.com";
            var scheme = "https";
            var uri = "/api/stuff/v1/asd/1234/visitors?from=20160301&to=20160303";
            var contentType = "application/json";
            var postContent = ""; // always empty string for Company API
            var date = DateTime.UtcNow;
            var dateString = date.ToString("r");
            

            // Build request signature
            var message = contentType + "\n" + domain + "\n" + uri + "\n" + dateString + "\n" + postContent + "\n";

            // Encode request signature
            var hmc = "";
            var encoding = new ASCIIEncoding();
            byte[] keyByte = encoding.GetBytes(privateKey);
            using (var hmacsha256 = new HMACSHA256(keyByte))
            {
                byte[] messageBytes = encoding.GetBytes(message);
                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                hmc = BitConverter.ToString(hashmessage).Replace("-", "").ToLower();
            }