-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
60 lines (47 loc) · 1.81 KB
/
Program.cs
File metadata and controls
60 lines (47 loc) · 1.81 KB
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.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.WebUtilities;
namespace JWTing
{
class Program
{
static void Main(string[] args)
{
string key = "Book-Key";
string jwt = GenerateJWT(key);
System.Console.WriteLine(jwt);
System.Console.WriteLine(VerifyJWT(jwt, key));
}
private static string GenerateJWT(string key)
{
using (HMAC mac = HMAC.Create("HMACSHA256"))
{
mac.Key = Encoding.UTF8.GetBytes(key);
var hdr = new { alg = "HS256", typ = "JWT" };
var payload = new { sub = "bookworm", role = "admin", aud = "BookClub" };
string hdrJson = Encode(hdr);
string payldJson = Encode(payload);
byte[] hash = mac.ComputeHash(Encoding.UTF8.GetBytes($"{hdrJson}.{payldJson}"));
string hashEncoded = WebEncoders.Base64UrlEncode(hash);
return $"{hdrJson}.{payldJson}.{hashEncoded}";
}
}
private static bool VerifyJWT(string jwt, string key)
{
string[] jwtParts = jwt.Split('.', StringSplitOptions.RemoveEmptyEntries);
using (HMAC mac = HMAC.Create("HMACSHA256"))
{
mac.Key = Encoding.UTF8.GetBytes(key);
byte[] hash = mac.ComputeHash(Encoding.UTF8.GetBytes($"{jwtParts[0]}.{jwtParts[1]}"));
string hashEncoded = WebEncoders.Base64UrlEncode(hash);
return hashEncoded == jwtParts[2];
}
}
private static string Encode(object value)
{
return WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(value)));
}
}
}