-
Notifications
You must be signed in to change notification settings - Fork 1
/
FastSpringFormValidator.cs
executable file
·60 lines (49 loc) · 1.67 KB
/
FastSpringFormValidator.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
using System;
using System.Collections.Specialized;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace SyntaxTree.FastSpring
{
internal static class FastSpringFormValidator
{
public static bool IsValidNotification(this NameValueCollection form, string privateKey)
{
const string dataParameter = "security_data";
const string hashParameter = "security_hash";
if (!form.HasParameter(dataParameter) || !form.HasParameter(hashParameter))
return false;
var value = form[dataParameter] + privateKey;
return form.HashMatches(hashParameter, value);
}
public static bool IsValidLicenseRequest(this NameValueCollection form, string privateKey)
{
const string hashParameter = "security_request_hash";
if (!form.HasParameter(hashParameter))
return false;
var value = form.AllKeys
.Where(k => k != hashParameter)
.OrderBy(k => k, StringComparer.Ordinal)
.Select(k => form[k])
.Aggregate(new StringBuilder(), (sb, v) => sb.Append(v))
.Append(privateKey)
.ToString();
return form.HashMatches(hashParameter, value);
}
private static bool HashMatches(this NameValueCollection form, string hashParameter, string value)
{
return form[hashParameter].ToLowerInvariant() == Md5HashOf(value);
}
private static bool HasParameter(this NameValueCollection form, string parameter)
{
return form[parameter] != null;
}
private static string Md5HashOf(string value)
{
return MD5.Create()
.ComputeHash(Encoding.UTF8.GetBytes(value))
.Aggregate(new StringBuilder(), (sb, b) => sb.Append(b.ToString("x2")))
.ToString();
}
}
}