Skip to content

Instantly share code, notes, and snippets.

@Porges
Created April 12, 2017 04:06
Show Gist options
  • Save Porges/23d3b3330f017280b9dc90ab6ca6e5ba to your computer and use it in GitHub Desktop.
Save Porges/23d3b3330f017280b9dc90ab6ca6e5ba to your computer and use it in GitHub Desktop.
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Microsoft.IdentityModel.Tokens;
namespace JWTTest
{
public static class Program
{
public static void Main()
{
bool x509 = true;
SigningCredentials signingCredentials;
EncryptingCredentials encryptingCredentials;
if (x509)
{
var chosenCert = FindAnyUsableCert();
var key = new X509SecurityKey(chosenCert);
signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature);
encryptingCredentials = new EncryptingCredentials(key, SecurityAlgorithms.RsaOAEP,
SecurityAlgorithms.Aes256CbcHmacSha512);
}
else
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(new string('s', 12345))); // the "s" is for "secure"
signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
encryptingCredentials = new EncryptingCredentials(key, "dir", SecurityAlgorithms.Aes256CbcHmacSha512);
}
var securityTokenDescriptor = new SecurityTokenDescriptor
{
IssuedAt = DateTime.MinValue,
NotBefore = DateTime.MinValue,
Expires = DateTime.MaxValue,
SigningCredentials = signingCredentials,
EncryptingCredentials = encryptingCredentials,
};
var handler = new JwtSecurityTokenHandler();
var token = handler.CreateToken(securityTokenDescriptor);
Console.WriteLine(handler.WriteToken(token));
}
private static X509Certificate2 FindAnyUsableCert()
{
using (var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
certStore.Open(OpenFlags.ReadOnly);
foreach (var cert in certStore.Certificates)
{
if (cert.HasPrivateKey)
{
try
{
var privKey = cert.GetRSAPrivateKey();
if (privKey.KeySize >= 2048)
{
return cert;
}
}
catch
{
// not exportable
}
}
}
}
throw new Exception("Couldn't find a usable certificate :(");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment