Wednesday, October 11, 2023

Generate EdDSA key pair in .NET and save it to json

EdDSA is one of the commonly used encryption algorithms atm. There is a trend to use it instead of older RSA alg. In .Net there are not that many resources about it. E.g. popular nuget package jose-jwt (Javascript Object Signing and Encryption) still doesn't support EdDSA. Fortunately there are another packages which support it:

but many basic examples are still missing. In this post I will show how to generate EdDSA key pair in .NET6 using above packages and save it in json format for later use.

Here is the code which generates key pair (before to run it install both nuget packages):

var keyPairGenerator = new Ed25519KeyPairGenerator();
keyPairGenerator.Init(new Ed25519KeyGenerationParameters(new SecureRandom()));
var keyPairParams = keyPairGenerator.GenerateKeyPair();

var privateKeyParams = (Ed25519PrivateKeyParameters)keyPairParams.Private;
var publicKeyParams = (Ed25519PublicKeyParameters)keyPairParams.Public;

var keyPair = new EddsaKeyPair { d = Base64UrlEncoder.Encode(privateKeyParams.GetEncoded()), x = Base64UrlEncoder.Encode(publicKeyParams.GetEncoded()) };

File.WriteAllText("keys.json", JsonConvert.SerializeObject(keyPair));

public class EddsaKeyPair
{
    public string kty => "OKP";
    public string alg => "EdDSA";
    public string crv => "Ed25519";
    public string x { get; set; } // public key
    public string d { get; set; } // private key
}

As result it will save EdDSA keys pair to keys.json file which will look like this:

{
	"kty": "OKP",
	"alg": "EdDSA",
	"crv": "Ed25519",
	"x": "...",
	"d": "..."
}

Here "x" property is used for public key and "d" is for private key. Having key pair you will be able e.g. sign and verify jwt tokens in your app.

Update 2024-01-09: see also next posts from this series Sign JWT tokens with EdDSA encryption algorithm and Verify JWT tokens with EdDSA encryption algorithm.