scottbrady91 / IdentityModel

JWT style token handlers for Branca and PASETO in .NET. EdDSA support for Microsoft.IdentityModel.
https://www.scottbrady91.com/c-sharp/replacing-jwts-with-branca-and-paseto-in-dotnet-core
Apache License 2.0
40 stars 10 forks source link

How to Import EdDsa keys from PEM? #14

Open Caliv0 opened 7 months ago

Caliv0 commented 7 months ago

Found this, which seems to get close. https://stackoverflow.com/questions/72152837/get-public-and-private-key-from-pem-ed25519-in-c-sharp

I'm unable to create an EdDsaSecurityKey object from it.

I'm new to BouncyCastle and EdDsa in general.

I'm trying to setup JWTs with EdDsa instead of HMACSHA256, but as stated before, I'm unable to import the keys.

Mako88 commented 2 months ago

After a lot of searching around, here's how I figured out to create and load a .pem private key:

First, generate your public/private .pem key files:

openssl genpkey -algorithm ed25519 -out jwt-private.pem
openssl pkey -in jwt-private.pem -pubout -out jwt-public.pem

Then convert the .pem files into the .der format:

openssl pkey -in jwt-private.pem -out jwt-private.der -outform DER
openssl pkey -in jwt-private.pem -pubout -out jwt-public.der -outform DER

Now load the private key from the .der file into an EdDsaSecurityKey:

var signingKeyBytes = await File.ReadAllBytesAsync("/path/to/jwt-private.der");

if (signingKeyBytes.Length == 0)
{
    throw new FileNotFoundException("Unable to read token signing key file");
}

var validationKeyBytes = await File.ReadAllBytesAsync("/path/to/jwt-public.der");

if (validationKeyBytes.Length == 0)
{
    throw new FileNotFoundException("Unable to read token validation key file");
}

var eddsa = EdDsa.Create(new EdDsaParameters(ExtendedSecurityAlgorithms.Curves.Ed25519)
{
    D = signingKeyBytes.TakeLast(32).ToArray(),
    X = validationKeyBytes.TakeLast(32).ToArray(),
});

return new EdDsaSecurityKey(eddsa);

Also, if you're using .NET 8, be sure to validate your token with the JsonWebTokenHandler, not the JwtSecurityTokenHandler