What is the correct way to Transform JWK to RSA key value Pair

1.3k views Asked by At

let's say we have the following JWK as an embedded resource in the project

enter image description here

the following code successfully reads the JSON into a JSONWebKey

 JsonWebKey jwk = ReadResource();

We want this to be transformed into a RSA key value Pair, so we have the following code that is expected to transform the JWK into a RSA KeyPair.

            UnicodeEncoding ByteConverter = new UnicodeEncoding();

            RSAParameters publicKey = new RSAParameters();
            RSAParameters privateKey = new RSAParameters();

            JsonWebKey jwk = ReadResource();

           // PUBLIC KEY

            publicKey.Exponent = ByteConverter.GetBytes(jwk.E);
            publicKey.Modulus = ByteConverter.GetBytes(jwk.N);

            // PRIVATE KEY

            privateKey.Exponent = ByteConverter.GetBytes(jwk.E);
            privateKey.Modulus = ByteConverter.GetBytes(jwk.N);
            privateKey.D = ByteConverter.GetBytes(jwk.D);
            privateKey.DP = ByteConverter.GetBytes(jwk.DP);
            privateKey.DQ = ByteConverter.GetBytes(jwk.DQ);
            privateKey.P = ByteConverter.GetBytes(jwk.P);
            privateKey.Q = ByteConverter.GetBytes(jwk.Q);
            privateKey.InverseQ = ByteConverter.GetBytes(jwk.QI);

But when we try to Sign the Data as follows

            RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider(2048);
            RSAalg.ImportParameters(privateKey);
            return RSAalg.SignData(DataToSign, SHA256.Create());

it throws CryptographicException @ RSAalg.ImportParameters(privateKey);

what is the correct way to transform a JWK into a RSA Key Pair using C#.net core.

0

There are 0 answers