使用字符串中的 public 键验证 JWT

Verify JWT using public key in string

我有以下格式的 public 密钥: -----BEGIN RSA PUBLIC KEY-----MIIBCgKCAQEA1pjRK+cOnEsh5L1wrt1Tmx+FvyNRj4wuAotlqIWtHS8pIqRzsIOJg+tlbUtEXYju+KOcIohZnnmfj0cq28RcQ19HIohqUXypmUbNy9np/M+Aj9NcyKIaNyuEZ+UhcU/OIStHK4eTUJt+RWL+0Q1/rl49tg7h+toB9Y6Y3SeytXvZhMx3N5qqmHHNorpfb65bvvHsicGDB7vK5kn55o+C2LhRIxfnw87nKnhPBMRbZg+BKCTXD4svz4a2xiR/uM4rxebIBgB3Sm4X1w3yoRr0F3IDhAgXmEhSZ078wm3ohPfuuwymfVhvdzavm42NwzixZ7n52SowFE2v0DSJh3IbPwIDAQAB-----END RSA PUBLIC 密钥-----

我如何实现 C# 以使用该字符串验证我的 JWT?我在 找到了类似的主题,但 none 的解决方案适合我的情况。

有我的代码:

        public static bool TransformKey(string fullKey)
        {
            try
            {
                var publicKey = fullKey.Replace("-----BEGIN RSA PUBLIC KEY-----", "");
                publicKey = publicKey.Replace("-----END RSA PUBLIC KEY-----", "");
                publicKey = publicKey.Replace("\n", "");

                var keyBytes = Convert.FromBase64String(publicKey); // your key here 
                AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(keyBytes);
                RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;
                RSAParameters rsaParameters = new RSAParameters
                {
                    Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned(),
                    Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned()
                };
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return false;
            }
        }
      
        static void Main(string[] args)
        {
            // The code provided will print ‘Hello World’ to the console.
            // Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.
            string key = "-----BEGIN RSA PUBLIC KEY-----MIIBCgKCAQEA1pjRK+cOnEsh5L1wrt1Tmx+FvyNRj4wuAotlqIWtHS8pIqRzsIOJg+tlbUtEXYju+KOcIohZnnmfj0cq28RcQ19HIohqUXypmUbNy9np/M+Aj9NcyKIaNyuEZ+UhcU/OIStHK4eTUJt+RWL+0Q1/rl49tg7h+toB9Y6Y3SeytXvZhMx3N5qqmHHNorpfb65bvvHsicGDB7vK5kn55o+C2LhRIxfnw87nKnhPBMRbZg+BKCTXD4svz4a2xiR/uM4rxebIBgB3Sm4X1w3yoRr0F3IDhAgXmEhSZ078wm3ohPfuuwymfVhvdzavm42NwzixZ7n52SowFE2v0DSJh3IbPwIDAQAB-----END RSA PUBLIC KEY-----";
            bool test = TransformKey(key);
            Console.ReadKey();
        }

当我尝试初始化 asymmetricKeyParameter 对象时出现 returns 异常:

System.ArgumentException: Unknown object in GetInstance: Org.BouncyCastle.Asn1.DerInteger
Parameter name: obj
   w Org.BouncyCastle.Asn1.Asn1Sequence.GetInstance(Object obj)
   w Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier.GetInstance(Object obj)
   w Org.BouncyCastle.Asn1.X509.SubjectPublicKeyInfo..ctor(Asn1Sequence seq)
   w Org.BouncyCastle.Asn1.X509.SubjectPublicKeyInfo.GetInstance(Object obj)
   w Org.BouncyCastle.Security.PublicKeyFactory.CreateKey(Byte[] keyInfoData)

可能有用的字符串类型的模数和指数代码段:

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.ImportParameters(
              new RSAParameters()
              {
                  Modulus = FromBase64Url("w7Zdfmece8iaB0kiTY8pCtiBtzbptJmP28nSWwtdjRu0f2GFpajvWE4VhfJAjEsOcwYzay7XGN0b-X84BfC8hmCTOj2b2eHT7NsZegFPKRUQzJ9wW8ipn_aDJWMGDuB1XyqT1E7DYqjUCEOD1b4FLpy_xPn6oV_TYOfQ9fZdbE5HGxJUzekuGcOKqOQ8M7wfYHhHHLxGpQVgL0apWuP2gDDOdTtpuld4D2LK1MZK99s9gaSjRHE8JDb1Z4IGhEcEyzkxswVdPndUWzfvWBBWXWxtSUvQGBRkuy1BHOa4sP6FKjWEeeF7gm7UMs2Nm2QUgNZw6xvEDGaLk4KASdIxRQ"),
                  Exponent = FromBase64Url("AQAB")
              });

对于 .NET Framework(例如 4.7.2),可以导入 public PKCS#1 密钥,例如使用 BouncyCastle(例如 v1.8.6.1):

using System.IO;
using System.Security.Cryptography;

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;

...

string publicPKCS1 = @"-----BEGIN RSA PUBLIC KEY-----
                       MIIBCgKCAQEA1pjRK+cOnEsh5L1wrt1Tmx+FvyNRj4wuAotlqIWtHS8pIqRzsIOJ
                       g+tlbUtEXYju+KOcIohZnnmfj0cq28RcQ19HIohqUXypmUbNy9np/M+Aj9NcyKIa
                       NyuEZ+UhcU/OIStHK4eTUJt+RWL+0Q1/rl49tg7h+toB9Y6Y3SeytXvZhMx3N5qq
                       mHHNorpfb65bvvHsicGDB7vK5kn55o+C2LhRIxfnw87nKnhPBMRbZg+BKCTXD4sv
                       z4a2xiR/uM4rxebIBgB3Sm4X1w3yoRr0F3IDhAgXmEhSZ078wm3ohPfuuwymfVhv
                       dzavm42NwzixZ7n52SowFE2v0DSJh3IbPwIDAQAB
                       -----END RSA PUBLIC KEY-----";

PemReader pemReader = new PemReader(new StringReader(publicPKCS1));
AsymmetricKeyParameter asymmetricKeyParameter = (AsymmetricKeyParameter)pemReader.ReadObject();
RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters((RsaKeyParameters)asymmetricKeyParameter);

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(rsaParameters);

...

JWT 的验证可以使用 JWT 库(例如 System.IdentityModel.Tokens.Jwt)或纯密码术 API 完成。 . Regarding the former, see also 第 2 段的答案中详细描述了两者。