Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to Import EdDsa keys from PEM? #14

Open
ghost opened this issue Apr 11, 2024 · 1 comment
Open

How to Import EdDsa keys from PEM? #14

ghost opened this issue Apr 11, 2024 · 1 comment

Comments

@ghost
Copy link

ghost commented Apr 11, 2024

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
Copy link

Mako88 commented Sep 8, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant