-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathverify.cs
67 lines (56 loc) · 2.22 KB
/
verify.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
namespace EnterpriseWebhooks
{
using System;
using System.Linq;
using Nancy;
using Nancy.IO;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
public class HomeModule : NancyModule
{
public HomeModule()
{
InitialiseRoutes();
}
internal void InitialiseRoutes()
{
Post("/", async _ =>
{
string signature = Request.Headers["X-MessageMedia-Signature"].FirstOrDefault();
if (string.IsNullOrEmpty(signature))
{
return new Response {StatusCode = HttpStatusCode.Unauthorized};
}
byte[] signatureBytes = Convert.FromBase64String(signature);
byte[] dataBytes = new byte[Request.Body.Length];
RequestStream.FromStream(Request.Body).Read(dataBytes, 0, (int) Request.Body.Length);
if (!VerifySignature(signatureBytes, dataBytes, Environment.GetEnvironmentVariable("PUBLIC_CERT_PATH")))
{
return new Response {StatusCode = HttpStatusCode.Unauthorized};
}
return await HandleCallbackData(dataBytes);
});
}
internal Response HandleCallbackData(byte[] payload)
{
// Custom logic here
return new Response { StatusCode = HttpStatusCode.OK };
}
public static bool VerifySignature(byte[] signature, byte[] data, string publicKeyPath)
{
var publicKey = ReadRsaKeyPair(publicKeyPath);
ISigner verifier = SignerUtilities.GetSigner(PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id);
verifier.Init(false, publicKey);
verifier.BlockUpdate(data, 0, data.Length);
return verifier.VerifySignature(signature);
}
internal static RsaKeyParameters ReadRsaKeyPair(string pemFileName)
{
var fileStream = System.IO.File.OpenText(pemFileName);
var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(fileStream);
return (RsaKeyParameters)pemReader.ReadObject();
}
}
}