Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

JWT token with ES256 not generating token correctly in C#

$
0
0

I am generating JWT token with ES256 Algorithm and with private key. Here is my code.

try{    string privateKeyPem = @"-----BEGIN EC PRIVATE KEY-----     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX     -----END EC PRIVATE KEY-----";    string privateKeyContent = privateKeyPem    .Replace("-----BEGIN EC PRIVATE KEY-----", "")    .Replace("-----END EC PRIVATE KEY-----", "")    .Replace("\n", "").Replace("\r", "");    // Parse PEM content    StringReader reader = new StringReader(privateKeyPem);    PemReader pemReader = new PemReader(reader);    AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();    ECPrivateKeyParameters privateKeyParams = (ECPrivateKeyParameters)keyPair.Private;    // Create an ECDsa instance    using (ECDsa ecdsa = ECDsa.Create())    {        // Import the private key parameters        ECParameters parameters = new ECParameters        {            Curve = ECCurve.NamedCurves.nistP256, // Or the appropriate curve for your key            D = privateKeyParams.D.ToByteArrayUnsigned(),            Q = new ECPoint            {                X = privateKeyParams.Parameters.G.AffineXCoord.ToBigInteger().ToByteArrayUnsigned(),                Y = privateKeyParams.Parameters.G.AffineYCoord.ToBigInteger().ToByteArrayUnsigned(),            }        };        // Import parameters into the ECDsa instance        ecdsa.ImportParameters(parameters);        string iss = "myiss";        string aud = "myaud";        string sub = "mysub";        string kid = "mykid";        string typ = "JWT";        // Construct JWT payload        var payload = new        {            iat = 1712647052,            iss = iss,            aud = aud,            exp = 1712657052,            sub = sub,            scope = "scope",            jti = "Mgergew"        };        var jwt = Jose.JWT.Encode(payload, ecdsa, JwsAlgorithm.ES256, extraHeaders: new Dictionary<string, object> { { "kid", kid }, { "typ", typ } });        Console.WriteLine("ECDSA private key imported successfully.");    }}catch (Exception ex){    Console.WriteLine($"Error: {ex.Message}");}

NOTE: Token is generating but I am not able to validate from this website.

https://dinochiesa.github.io/jwt/

Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>