首页 > 解决方案 > 在 C# 中使用 JSONWebKey 或 JSONWebKeySet 解密 JSONWebToken

问题描述

我一直在互联网上尝试各种解决方案,但所有解决方案都以各种方式破坏。我写信是希望 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 编码时),所以五个部分。

标签: c#jwtrsaadal

解决方案


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

正如您已经发现的那样,IdentityModel 目前不支持 RSA-OAEP-256。在实现之前使用 RSA_15 对我来说不是一个选择,但 .NET 支持 RSA-OAEP-256,所以我使用 CryptoProviderFactory 将其委托给我自己的实现(这基本上是对 .NET 的调用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

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


推荐阅读