This blog is useful to all my friends who are working on the .Net Technology and wants to enhance their skills as well their problem solving ability.

Friday, July 7, 2017

HMACSHA256 based API call using WebRequest

private void button1_Click(object sender, EventArgs e)
       {
           try
           {
               WebRequest request = WebRequest.Create("DemoAPI");
               request.ContentType = "application/json; charset=utf-8";
               string authInfo = Signature("test""Keys1""keys2");
               request.Headers["Authentication"] = authInfo;
               request.Method = "POST";
               request.ContentLength = 0;
               var response = request.GetResponse();
           }
           catch (Exception ex)
           {
               throw ex;
           }
       }
 
       public string Signature(string secret, string value, string key2)
       {
           var secretBytes = Encoding.UTF8.GetBytes(secret);
           var valueBytes = Encoding.UTF8.GetBytes(value);
           string signature;
 
           using (var hmac = new HMACSHA256(secretBytes))
           {
               var hash = hmac.ComputeHash(valueBytes);
               signature = Convert.ToBase64String(hash);
           }
           //return signature;
           return key2 + ":" + signature;
       }