Created
January 9, 2021 22:14
-
-
Save jlewin/39fc69f8217d98131777484aea5ee333 to your computer and use it in GitHub Desktop.
JWT signature compute in c#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// From stackoverflow and adapted to unusure it makes sense with our data | |
// -- https://stackoverflow.com/questions/38725038/c-sharp-how-to-verify-signature-on-jwt-token | |
void Main() | |
{ | |
var jwt = "some-jwt"; | |
var segments = jwt.Split('.'); | |
var decoded = segments.Select(s => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(s))); | |
// Cleaner | |
var headerAndPayload = jwt.Substring(0, jwt.LastIndexOf('.')); | |
Console.WriteLine(headerAndPayload); | |
// Segmented... | |
// var headerAndPayload1 = String.Join(".", segments.Take(2)); | |
// Console.WriteLine(headerAndPayload1); | |
var jwtSignatureSecret = "secret"; | |
var bytesToSign = Encoding.UTF8.GetBytes(headerAndPayload); | |
var hmacAlg = new System.Security.Cryptography.HMACSHA256(Encoding.UTF8.GetBytes(jwtSignatureSecret)); | |
var hash = hmacAlg.ComputeHash(bytesToSign); | |
Console.WriteLine("Expected: " + Base64UrlEncode(hash)); | |
Console.WriteLine("Actual : " + segments.Last()); | |
} | |
// from JWT spec | |
private static string Base64UrlEncode(byte[] input) { | |
var output = Convert.ToBase64String(input); | |
output = output.Split('=')[0]; // Remove any trailing '='s | |
output = output.Replace('+', '-'); // 62nd char of encoding | |
output = output.Replace('/', '_'); // 63rd char of encoding | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment