-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNexmoHMAC.cs
51 lines (42 loc) · 1.7 KB
/
NexmoHMAC.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
namespace Lorond.Nexmo
{
public static class Example
{
public static void SignRequestWithHMAC()
{
// Depends on Newtonsoft's Json.NET library
const string apiKey = "API_KEY";
const string securitySecret = "SECURITY_SECRET";
var parameters = new SortedDictionary<string, object>
{
["api_key"] = apiKey,
["to"] = "<recipient>",
["from"] = "<sender>",
["text"] = "Hello from Nexmo",
["type"] = "text",
["timestamp"] = (long)Math.Floor((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds),
};
var data = new StringBuilder();
foreach (var pair in parameters)
data.AppendFormat("&{0}={1}", pair.Key, pair.Value);
var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(securitySecret));
var signatureBin = hmac.ComputeHash(Encoding.UTF8.GetBytes(data.ToString()));
var signature = string.Join(string.Empty, signatureBin.Select(x => x.ToString("x2")));
using (var wc = new WebClient())
{
wc.Headers["Content-Type"] = "application/json";
parameters["sig"] = signature;
var json = JsonConvert.SerializeObject(parameters, Formatting.Indented);
var response = wc.UploadString(@"https://rest.nexmo.com/sms/json", json);
Console.WriteLine(response);
}
}
}
}