IdentityModel icon indicating copy to clipboard operation
IdentityModel copied to clipboard

How to Import EdDsa keys from PEM?

Open ghost opened this issue 1 year ago • 1 comments

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.

ghost avatar Apr 11 '24 20:04 ghost

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

Mako88 avatar Sep 08 '24 03:09 Mako88