Use PEM encoded RSA private key in .NET

前端 未结 5 2027
囚心锁ツ
囚心锁ツ 2021-01-06 22:21

I have a private key which looks like this:

-----BEGIN RSA PRIVATE KEY----- Some private key data -----END RSA PRIVA

5条回答
  •  广开言路
    2021-01-06 22:55

    First, you need to transform the private key to the form of RSA parameters using Bouncy Castle library. Then you need to pass the RSA parameters to the RSA algorithm as the private key. Lastly, you use the JWT library to encode and sign the token.

        public string GenerateJWTToken(string rsaPrivateKey)
        {
            var rsaParams = GetRsaParameters(rsaPrivateKey);
            var encoder = GetRS256JWTEncoder(rsaParams);
    
            // create the payload according to your need
            var payload = new Dictionary
            {
                { "iss", ""},
                { "sub", "" },
                // and other key-values 
            };
    
            var token = encoder.Encode(payload, new byte[0]);
    
            return token;
        }
    
        private static IJwtEncoder GetRS256JWTEncoder(RSAParameters rsaParams)
        {
            var csp = new RSACryptoServiceProvider();
            csp.ImportParameters(rsaParams);
    
            var algorithm = new RS256Algorithm(csp, csp);
            var serializer = new JsonNetSerializer();
            var urlEncoder = new JwtBase64UrlEncoder();
            var encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
    
            return encoder;
        }
    
        private static RSAParameters GetRsaParameters(string rsaPrivateKey)
        {
            var byteArray = Encoding.ASCII.GetBytes(rsaPrivateKey);
            using (var ms = new MemoryStream(byteArray))
            {
                using (var sr = new StreamReader(ms))
                {
                    // use Bouncy Castle to convert the private key to RSA parameters
                    var pemReader = new PemReader(sr);
                    var keyPair = pemReader.ReadObject() as AsymmetricCipherKeyPair;
                    return DotNetUtilities.ToRSAParameters(keyPair.Private as RsaPrivateCrtKeyParameters);
                }
            }
        }
    

    ps: the RSA private key should have the following format:

    -----BEGIN RSA PRIVATE KEY-----

    {base64 formatted value}

    -----END RSA PRIVATE KEY-----

提交回复
热议问题