【问题标题】:Decrypting JSONWebToken Using JSONWebKey or JSONWebKeySet in C#在 C# 中使用 JSONWebKey 或 JSONWebKeySet 解密 JSONWebToken
【发布时间】:2021-09-07 09:36:55
【问题描述】:

我一直在互联网上尝试各种解决方案,但所有解决方案都以各种方式出现故障。我写信是希望 StackOverflow 上熟悉类似工作流程的人或 Microsoft.IdentityModel.JsonWebTokens 团队的人可以介入以提供帮助。

我要做的是解密由 JSONWebKey (JWK) 加密的 OAuth 访问令牌,以便我可以读取声明数据。现在我被困在解密步骤上。我在 OS X 上使用 C# 和 Visual Studio for Mac。我尝试过的方法包括使用较旧的 JWT 库并尝试通过迂回方式创建各种 RSA 对象。但是,我想做的是如下所示:

using System;
using System.Linq;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using System.Security.Cryptography;
using Microsoft.AspNetCore.WebUtilities;

namespace jwtdecoder {
    class Program {
        static void Main(string[] args) {
            
            /* Exact string of a token retrieved from the IDP/OAuth server. */
            String token = "BASE64EncodedTokenGoesHere";

            /* Trust me that we have a valid JWKS string here that has all the properties mentioned in the RSA params below 
             * and uses RSA OAEP 256 */
            String jwks = "JWKSSTRINGGOESHERE";


            /* Get our basic objects from the Strings above. */
            JsonWebKeySet exampleJWKS = new JsonWebKeySet(jwks);
            JsonWebKey exampleJWK = exampleJWKS.Keys.First();
            JsonWebToken exampleJWT = new JsonWebToken(token);

            /* Create RSA from Elements in JWK */
            RSAParameters rsap = new RSAParameters{
                Modulus = WebEncoders.Base64UrlDecode(exampleJWK.N),
                Exponent = WebEncoders.Base64UrlDecode(exampleJWK.E),
                D = WebEncoders.Base64UrlDecode(exampleJWK.D),
                P = WebEncoders.Base64UrlDecode(exampleJWK.P),
                Q = WebEncoders.Base64UrlDecode(exampleJWK.Q),
                DP = WebEncoders.Base64UrlDecode(exampleJWK.DP),
                DQ = WebEncoders.Base64UrlDecode(exampleJWK.DQ),
                InverseQ = WebEncoders.Base64UrlDecode(exampleJWK.QI)
            };
            RSA rsa = RSA.Create();
            rsa.ImportParameters(rsap);
            RsaSecurityKey rsakey = new RsaSecurityKey(rsa);

            /* Create a JSON Token Handler and Try Decrypting the Token */
            JsonWebTokenHandler exampleHandler = new JsonWebTokenHandler();
            TokenValidationParameters validationParameters = new TokenValidationParameters {
                ValidateAudience = false,
                ValidateIssuer = false,
                RequireSignedTokens = false, /* Have also tried with this set to True */
                TokenDecryptionKey = rsakey
            };

            String clearToken = exampleHandler.DecryptToken(exampleJWT, validationParameters);
            /* The line above results in an error
             * "IDX10609: Decryption failed. No Keys tried: token: 'System.String'."
             */
        }
    }
}

我的 IDP/OAuth 服务器是 Micro Focus / NetIQ Access Manager,使用我在其外部生成的 JSON Web 密钥(并作为新的资源服务器导入)。但是,我认为细节与问题没有太大关系。当我在 C# 中创建 JSONWebKey 和 JSONWebToken 对象时,我看到了我希望看到的属性,并且没有任何异常。我还可以使用非 C# 工具解码(而不是解密)令牌字符串,并查看我期望的标头属性等。

具体来说,对于上面代码中的exampleJWT对象,header如下:

{{ "alg": "RSA-OAEP-256", "enc": "A128CBC-HS256", "typ": "JWT", "cty": "JWT", "zip": "DEF", "kid": "5BbVY7F77gz9LWE4tUjXwNFt9qhINvWBR7Pkm1ZJlEA" }}

exampleJWT 对象还具有以下属性,其值看起来要么已编码要么已加密:EncodedHeader、EncodedToken、EncryptedKey、CipherText 和 AuthenticationTag 目前该对象中没有明文索赔数据或日期数据。

我的想法是我没有为 Decrypt 方法正确设置我的代码以正确应用 JSONWebToken RSA 信息,以便可以将令牌转换为明文。然而,正如我所说,我使用其他 C# 类和方法尝试了许多不同的方法,但没有一个更成功。我很想知道我对这个过程的根本误解。提前谢谢你。

在下面回答 Michal 的问题:四个点(base-64 编码时),所以五个部分。

【问题讨论】:

  • 从这里的描述听起来你想要解码令牌并验证签名,而不是解密它,但也许我没有看到任何东西。快速检查一下 - 您的 JWT 是由点分隔的三个部分还是五个部分?
  • 是的,现在更清楚的是,您确实在解密令牌。你试过调试吗?在代码中的某处放置断点并检查库中发生的情况。令牌是否正确传递? (收到System.string的消息有点奇怪,还是正常的?)

标签: c# jwt rsa adal


【解决方案1】:

感谢 Michal 确认我正在做的事情应该有效,并促使我调试 JSONWebToken Nuget 包。由于 NuGet 包中没有包含调试信息,我从源代码构建了 Microsoft.IdentityModel.JsonWebTokens 并逐步解决了这些问题。

有两个问题,都是致命的。

  1. JWT 解密密钥 ID 需要与提供的解密密钥 ID 匹配,并且我没有将 KID 从 JWKS 复制到 RSA 对象。在修复此问题时,我还复制了密钥大小,尽管默认值会起作用。我的示例代码需要更改如下:

    /* Existing code. */
    RSA rsa = RSA.Create();
    rsa.ImportParameters(rsap);
    RsaSecurityKey rsakey = new RsaSecurityKey(rsa);
    /* New stuff here. */
    rsakey.KeyId = exampleJWK.KeyId;
    rsa.KeySize = exampleJWK.KeySize;
    
  2. 第二个问题应该会在几个月后在包含 Microsoft.IdentityModel.JsonWebTokens 命名空间的 ADAL 库的未来版本中得到解决。尽管 dotnet 通常在所有平台上都支持 RSA-OAEP-256,但 ADAL 的 JSONWebToken 实现尚不支持它。
    跨平台支持注意:
    https://docs.microsoft.com/en-us/dotnet/standard/security/cross-platform-cryptography
    关于 ADAL 和 RSA-OAEP-256 的 GitHub 问题:
    https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/1293

我使用 RSA_15 生成并安装了一个新的 JWKS,从 Access Manager 获取了一个新的 OAuth JWT,并且我的代码正常工作。最后,我得到了一个字符串,我可以将它放入一个新的 JSONWebToken 对象中,并且所有字段(声明、日期等)都存在且正确。

对于那些想知道这一切有什么意义的人,我真的很喜欢 C# 和 Microsoft 的新库,但更喜欢在 Mac 上开发并部署到 Linux。我真的很喜欢 NAM(访问管理器)作为本地 SAML/OAuth 解决方案。但我想使用它们在资源服务器/应用程序中解密令牌,而不是将它们发送回 NAM 进行验证和解密(更快且移动部件更少)。所以现在我可以做到了。一旦库支持 RSA-OAEP-256,我将替换 JWKS 以获得更好的安全性。

最后,回答 Michal 的最后一个问题,根据上面的 GitHub 链接,System.string 引用异常是当前实现的一部分,但显然不应该。

【讨论】:

    【解决方案2】:

    大约 3 周前我也遇到了这个问题。

    您已经发现,IdentityModel 目前不支持 RSA-OAEP-256。 在实现之前使用 RSA_15 对我来说不是一个选择,但是 .NET 支持 RSA-OAEP-256,所以我利用 CryptoProviderFactory 将其委托给我自己的实现(这基本上是对 Decrypt 的调用) .

    首先你需要用 ICryptoProvider 接口实现一个类:

    public class CryptoProvider : ICryptoProvider
    {
        public bool IsSupportedAlgorithm(string algorithm, params object[] args)
        {
          if (algorithm == "RSA-OAEP-256")
            return true;
    
          return false;
        }
    
        public object Create(string algorithm, params object[] args)
        {
          if (algorithm.Equals("RSA-OAEP-256"))
            return new RsaOaepKeyWrapProvider(args[0] as SecurityKey, algorithm, (bool)args[1]);
    
          return null;
        }
    
        public void Release(object cryptoInstance)
        {
          throw new NotImplementedException();
        }
    }
    

    然后你需要从 KeyWrapProvider 派生:

    public class RsaOaepKeyWrapProvider : KeyWrapProvider
    {
        public RsaOaepKeyWrapProvider(SecurityKey key, string algorithm, bool willUnwrap)
        {
          Key = key;
          Algorithm = algorithm;
        }
    
        protected override void Dispose(bool disposing)
        {
        }
    
        public override byte[] UnwrapKey(byte[] keyBytes)
        {
          //Get your RSA Object
          var rsa = CryptoConfig.GetRSA();
          return rsa.Decrypt(keyBytes, RSAEncryptionPadding.OaepSHA256);
        }
    
        //We don't need Key Wrapping
        public override byte[] WrapKey(byte[] keyBytes)
        {
          throw new NotImplementedException();
        }
    
        public override string Algorithm { get; }
        public override string Context { get; set; }
        public override SecurityKey Key { get; }
    }
    

    最后,您需要将 rsakey.CryptoProviderFactory 设置为您的 CryptoProvider 类的实例。

    除了并非所有 KeyWrapProvider 都受支持之外,IdentityModel.Tokens 还缺乏对 AES-GCM 的身份验证加密的支持。通过对上述实现进行一些调整,您也可以支持这一点。 当这最终在库中实现时,您可以删除附加代码而无需更改其他实现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-17
      • 2019-02-20
      • 2011-08-20
      • 2017-05-26
      • 1970-01-01
      • 2022-01-26
      • 2013-07-15
      • 2010-11-03
      相关资源
      最近更新 更多