Search code examples
c#resthmacsinch

Using Sinch REST Api in C#


I am trying to use Sinch REST api in c# for sms verification and I am having trouble encoding the strings required for Authorization. I am using APPLICATION SIGNED REQUEST for Auth and I would like to know what c# functions to use to created the content-Md5 and stringtoSign. For content MD-5 here is the code snippet I have

var body = JsonConvert.SerializeObject(smsRequest);

var hs = System.Security.Cryptography.MD5.Create();

var db = hs.ComputeHash(Encoding.UTF8.GetBytes(body));

var stringToSign = Convert.ToBase64String(db);

 public class SmsRequest
{
    [JsonProperty("identity")]
    public Identity Identity;

    [JsonProperty("method")]
    public string Method;

    [JsonProperty("metadata")]
    public Metadata Metadata;
}

public class Metadata
{
    [JsonProperty("os")]
    public string Os;

    [JsonProperty("platform")]
    public string Platform;

}

public class Identity
{
    [JsonProperty("type")]
    public string Type;

    [JsonProperty("endpoint")]
    public string Endpoint;
}

Now for creating the stringtoSign is something I use the following code

var stringToSign = "POST" + Environment.NewLine + "jANzQ+rgAHyf1MWQFSwvYw==" + Environment.NewLine +
                  "application/json" + Environment.NewLine + "x-timestamp:2014-06-04T13:41:58Z" +
                  Environment.NewLine + "/v1/sms/+46700000000";//used for signing

var secret = "JViE5vDor0Sw3WllZka15Q=="; // this needs to be signed
var encoding = new System.Text.UTF8Encoding();
byte[] keyByte = encoding.GetBytes(stringToSign);

var hmacsha256 = new HMACSHA256(keyByte);

byte[] messageBytes = Encoding.UTF8.GetBytes(secret);
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);

var res = Convert.ToBase64String(hashmessage);

I am using the values in the example here https://www.sinch.com/using-rest/ and I expect the result to be "qDXMwzfaxCRS849c/2R0hg0nphgdHciTo7OdM6MsdnM=" while using my method I am getting "2/8KqdiC2708EC84vTinPchiATRJiZU4Mgfpykb4F40=".

What is it that I am doing wrong here?


Solution

  • I would use our awesome nuget https://github.com/sinch/nuget-serversdk if you dont want to install the nuget you can check the source and take the pieces you want. its opensource and you