创建密钥时,JWT解码失败

时间:2019-06-11 08:31:24

标签: c# cryptography jwt

我已经借助stackoverflow编写了以下内容来解码JWT令牌。我认为公钥似乎存在问题。 因为它仅在密钥创建时失败。

class Program
{
    static void Main(string[] args)
    {
        string token = "TOKEN STRING";
        string key = "KEY STRING";

        string result = ValidateJWT(token, key);
        Console.WriteLine(result);
    }

    public static string ValidateJWT(string tokenTodecode, string publicKey)
    {
        string[] parts = tokenTodecode.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);


        var keyBytes = Convert.FromBase64String(publicKey); 

        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, FromBase64Url(parts[2])))
        {
            return "";
        }    

        return payloadData.ToString();
    }
    public static byte[] Base64UrlDecode(string arg)
    {
        var decrypted = ToBase64(arg);

        return Convert.FromBase64String(decrypted);
    }

    public static string ToBase64(string arg)
    {
        if (arg == null)
        {
            throw new ArgumentNullException("arg");
        }

        var s = arg
                .PadRight(arg.Length + (4 - arg.Length % 4) % 4, '=')
                .Replace("_", "/")
                .Replace("-", "+");

        return s;
    }

    static byte[] FromBase64Url(string base64Url)
    {
        string padded = base64Url.Length % 4 == 0
            ? base64Url : base64Url + "====".Substring(base64Url.Length % 4);
        string base64 = padded.Replace("_", "/")
                              .Replace("-", "+");
        return Convert.FromBase64String(base64);
    }
}

以下是我得到的错误。有人可以帮我解决这个问题吗?

enter image description here

是不是键不正确?

0 个答案:

没有答案