验证JWT签名ASP.NET C#

时间:2019-03-21 16:06:06

标签: c# asp.net jwt access-token

我对JWT非常陌生,一直在对此进行研究,但找不到正确的解决方案。我有一个JWT,它已经过期,但是当我使用公共密钥在JWT.IO上验证签名时,它就被验证了。该算法为RS256。当我在JWT.io上输入Im时,我用“ --- BEGIN CERTIFICATE ----”和“ --- END CERTIFICATE ----”包装公钥,并验证了JWT。

现在我使用以下功能在C#上尝试相同的事情:

public  string Decode(string token, string key, bool verify = true)
        {
            string[] parts = token.Split('.');
            string header = parts[0];
            string payload = parts[1];
            byte[] crypto = Base64UrlDecode(parts[2]);

            string headerJson = Encoding.UTF8.GetString(Base64UrlDecode(header));
            JObject headerData = JObject.Parse(headerJson);

            string payloadJson = Encoding.UTF8.GetString(Base64UrlDecode(payload));
            JObject payloadData = JObject.Parse(payloadJson);

            if (verify)
            {
                var keyBytes = Convert.FromBase64String(key); // your key here


                AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(keyBytes);
                RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;
                RSAParameters rsaParameters = new RSAParameters();
                rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
                rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.ImportParameters(rsaParameters);

                SHA256 sha256 = SHA256.Create();
                byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(parts[0] + '.' + parts[1]));

                RSAPKCS1SignatureDeformatter rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa);
                rsaDeformatter.SetHashAlgorithm("SHA256");
                if (!rsaDeformatter.VerifySignature(hash, Convert.FromBase64String(parts[2])))
                    throw new ApplicationException(string.Format("Invalid signature"));
            }

            return payloadData.ToString();
        }

但是,该行AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(keyBytes);引发异常消息“错误的序列大小:3 参数名称:seq”。

任何人都知道为什么会发生这种情况或以其他任何正确的方式签署JWT吗?

谢谢!

0 个答案:

没有答案