how to sign bytes using my own rsa private key using rs256 algorithm?

后端 未结 4 614
闹比i
闹比i 2020-12-04 03:03

I have my own private key string, i.e.

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

MIICXAIBAAKBgQCSAYYgzvGTww....
....
....
.....
3yUMYj9oYzqdrRHP0XgD0cEEvyqPBwLaNsRdFw         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-04 03:55

    The key to this question is using JWT and Bouncy castle libraries for encoding the token and signing it respectively.

    1. JWT for encoding and decoding JWT tokens
    2. Bouncy Castle supports encryption and decryption, especially RS256 get it here

    First, you need to transform the private key to the form of RSA parameters. 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-----

提交回复
热议问题