Skip to content

Instantly share code, notes, and snippets.

@ruze00
Created September 29, 2016 20:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruze00/10edfb63098f734f8c4d5ec13be359d9 to your computer and use it in GitHub Desktop.
Save ruze00/10edfb63098f734f8c4d5ec13be359d9 to your computer and use it in GitHub Desktop.
JWTS Token encoding using .NET for Jersey
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace TestAuth
{
class Program
{
static void Main(string[] args)
{
String applicationKey= "f5GmsZVC48CoOt2p";
String tokenHeaderName="X-Session-Token";
long expiredTokenPeriod=4000000;
String token = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ7XCJkaWdlc3RcIjpcImQzZGE0MjFiZGJjMGU5MmRmNGVkYWI2MjhiMjA1M2ExXCIsXCJ1aWRcIjpcIjAxNTk5MjFcIixcInRva2VuR2VuZXJhdGlvblRpbWVcIjpcIjIwMTY6MDk6Mjk6MTY6NDE6MzFcIn0ifQ.SFQB8l7MpK7ojgarLW8ssvZPvhB9p_zEaZrE5kxCMOY91GoXjEZOMg64NqHj0tRGywXcsc4v9jMcYxL3lN0bDw";
var handler = new JwtSecurityTokenHandler();
var output = handler.ReadToken(token);
string uid = "0159921";
string time = "2016:09:29:16:41:31";
string toMD5 = uid + time + applicationKey;
string digest;
using (MD5 md5 = MD5.Create())
{
digest = GetMd5Hash(md5, toMD5);
}
JwtHeader header = new JwtHeader
{
{"alg", "HS512"}
};
//string digest = "d3da421bdbc0e92df4edab628b2053a1";
JwtPayload payload = new JwtPayload
{
{
"sub",
"{\"digest\":\""+digest+"\",\"uid\":\""+uid+"\",\"tokenGenerationTime\":\""+time+"\"}"
}
};
var newToken = new JwtSecurityToken(header, payload);
var newStringToken = handler.WriteToken(newToken);
}
static string GetMd5Hash(MD5 md5Hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment