Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Json web key in the instantation of an RSA instance

I have a json web key(https://datatracker.ietf.org/doc/html/draft-ietf-jose-json-web-key-41) and I want to use it to sign some data with the private key and then later verify it with the public key. I am using c# with .net framework 4.5.1 and I can't seem to instantiate the classes properly using the keys I have. I generated the keys using this tool: https://github.com/mitreid-connect/json-web-key-generator. The following json is available and from this I should be able to sign and verify:

{
  "kty": "RSA",
  "d": "rZ_cdME7usL5EavJW1q0cjz8dhfdO9P-E4dacHYFf4I-TN7o-Q0ksfWCb4fpQPghUoz6v2b6-m3IZk4CocmdEAoFH2JqI0PbH5HIBqgva-bE8-elNJIKwza0Hbrw13bRU6KgpOrc9hrX-NcRCTkeKHYtDWGUa2NDB_lNQvkyg-V0NVXf5oSa_cZ9_H4kHPXrzcBeQapn2M_CFb3qfYgVgQb5xU5n67eAcSlztWHIaSaLyu_YAR0SxnEAvWiik1rtSYrEOWsVrPHfHBFwVHluP0g--bedH6kI3mZRI6H_UbmTMnRtxBkCA5mVdzOmsyX2e98MUqIlOeDQ4zB21xSDQQ",
  "e": "AQAB",
  "use": "sig",
  "alg": "RS512",
  "n": "xwHPJaSvKvLqrqb6oeXDL3A4iNgRo5PEQOQCE5zGa6ZWeoC88IuJZxXFJ93wzJk0J22QZJWofC8vV8GAeB3d9mD25koh0dbtb0yoWK-ttWamMIAN4WPiZu30JWzxY1k8LRzOz5lIT9Ze87gV_lgXbpkzQzKFNhxOmV_BhEu1PCLcOTHhic93WQk_E97nYCOwOifmkEFOCBzHEuTG1XHJ1nGEfBCAsdUXrMg_lU3w86TfVDYS6xLVtfVAq4ihDjBsmtPthrdMG4H5Qls8EM-_cbIRe7UEAQK9MgXDLHaQZbx_lQ46_P852SpCprbvqWaoM8zKyEiDf1q6O89D6YIaDw"
}

Then in C# I have a model with those fields and I made a function to test if I can verify data:

public class RSAKeyPair
{
    public string kty { get; set; }
    public string e { get; set; }
    public string use { get; set; }
    public string alg { get; set; }
    public string n { get; set; }
    public string d { get; set; }
}

And the test code:

public static bool TestSigning(RSAKeyPair keySet)
{
    if (keySet.alg != "RS512")
    {
        throw new ArgumentException("Only RS512 is supported.");
    }

    var oid = CryptoConfig.MapNameToOID("SHA512");

    RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();
    rsaProvider.ImportParameters(
        new RSAParameters()
        {
            Modulus = FromBase64Url(keySet.n),
            Exponent = FromBase64Url(keySet.e),
            D = FromBase64Url(keySet.d)
        }
    );

    var hasher = SHA512.Create();

    var testmsg = System.Text.Encoding.UTF8.GetBytes("TestMsg");
    var hash = hasher.ComputeHash(new MemoryStream(testmsg));

    var signedData = rsaProvider.SignHash(hash, oid);
    var isSigned = rsaProvider.VerifyHash(hash, oid, signedData);

    return isSigned;
}

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

However when I run it. I get the System.Security.Cryptography.CryptographicException with the message Object contains only the public half of a key pair. A private key must also be provided. when trying to get the signedData

I have no idea which parameters to set because this seems correct according to what I understand from RSA and reading the docs.

I have also tried to create two instances of the RSACryptoServiceProvider One signer with Exponent = keySet.d and one verifier with Exponent = keySet.e. But when I call RSACryptoServiceProvider.ImportParameters for the signer it throws a Bad data exception.

Any help is appreciated.

like image 589
CryptoNoob Avatar asked Feb 28 '18 17:02

CryptoNoob


1 Answers

The main reason is RSACryptoServiceProvider is not able to generate a private key using modulus, public and private exponent i.e n, e and d only, it requires p,q,dp and dq as well. To generate RsaParameters with private key you will require following code to calculate p,q,dp and dq and finally generate RsaParameters:

private static RSAParameters RecoverRSAParameters(BigInteger n, BigInteger e, BigInteger d)
{
    using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
    {
        BigInteger k = d * e - 1;

        if (!k.IsEven)
        {
            throw new InvalidOperationException("d*e - 1 is odd");
        }

        BigInteger two = 2;
        BigInteger t = BigInteger.One;

        BigInteger r = k / two;

        while (r.IsEven)
        {
            t++;
            r /= two;
        }

        byte[] rndBuf = n.ToByteArray();

        if (rndBuf[rndBuf.Length - 1] == 0)
        {
            rndBuf = new byte[rndBuf.Length - 1];
        }

        BigInteger nMinusOne = n - BigInteger.One;

        bool cracked = false;
        BigInteger y = BigInteger.Zero;

        for (int i = 0; i < 100 && !cracked; i++)
        {
            BigInteger g;

            do
            {
                rng.GetBytes(rndBuf);
                g = GetBigInteger(rndBuf);
            }
            while (g >= n);

            y = BigInteger.ModPow(g, r, n);

            if (y.IsOne || y == nMinusOne)
            {
                i--;
                continue;
            }

            for (BigInteger j = BigInteger.One; j < t; j++)
            {
                BigInteger x = BigInteger.ModPow(y, two, n);

                if (x.IsOne)
                {
                    cracked = true;
                    break;
                }

                if (x == nMinusOne)
                {
                    break;
                }

                y = x;
            }
        }

        if (!cracked)
        {
            throw new InvalidOperationException("Prime factors not found");
        }

        BigInteger p = BigInteger.GreatestCommonDivisor(y - BigInteger.One, n);
        BigInteger q = n / p;
        BigInteger dp = d % (p - BigInteger.One);
        BigInteger dq = d % (q - BigInteger.One);
        BigInteger inverseQ = ModInverse(q, p);

        int modLen = rndBuf.Length;
        int halfModLen = (modLen + 1) / 2;

        return new RSAParameters
        {
            Modulus = GetBytes(n, modLen),
            Exponent = GetBytes(e, -1),
            D = GetBytes(d, modLen),
            P = GetBytes(p, halfModLen),
            Q = GetBytes(q, halfModLen),
            DP = GetBytes(dp, halfModLen),
            DQ = GetBytes(dq, halfModLen),
            InverseQ = GetBytes(inverseQ, halfModLen),
        };
    }
}

private static BigInteger GetBigInteger(byte[] bytes)
{
    byte[] signPadded = new byte[bytes.Length + 1];
    Buffer.BlockCopy(bytes, 0, signPadded, 1, bytes.Length);
    Array.Reverse(signPadded);
    return new BigInteger(signPadded);
}
private static byte[] GetBytes(BigInteger value, int size)
{
    byte[] bytes = value.ToByteArray();

    if (size == -1)
    {
        size = bytes.Length;
    }

    if (bytes.Length > size + 1)
    {
        throw new InvalidOperationException($"Cannot squeeze value {value} to {size} bytes from {bytes.Length}.");
    }

    if (bytes.Length == size + 1 && bytes[bytes.Length - 1] != 0)
    {
        throw new InvalidOperationException($"Cannot squeeze value {value} to {size} bytes from {bytes.Length}.");
    }

    Array.Resize(ref bytes, size);
    Array.Reverse(bytes);
    return bytes;
}

private static BigInteger ModInverse(BigInteger e, BigInteger n)
{
    BigInteger r = n;
    BigInteger newR = e;
    BigInteger t = 0;
    BigInteger newT = 1;

    while (newR != 0)
    {
        BigInteger quotient = r / newR;
        BigInteger temp;

        temp = t;
        t = newT;
        newT = temp - quotient * newT;

        temp = r;
        r = newR;
        newR = temp - quotient * newR;
    }

    if (t < 0)
    {
        t = t + n;
    }

    return t;
}

Now to continue with JWK use it like following:

public static bool TestSigning(RSAKeyPair keySet)
{
    if (keySet.alg != "RS512")
    {
        throw new ArgumentException("Only SHA512 is supported.");
    }


    var n = GetBigInteger(FromBase64Url(keySet.n));
    var d = GetBigInteger(FromBase64Url(keySet.d));
    var e = GetBigInteger(FromBase64Url(keySet.e));

    var rsaParams= RecoverRSAParameters(n, e, d);

    RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(512);
    rsaProvider.ImportParameters(rsaParams);

    var hasher = SHA512.Create();

    var testmsg = Encoding.UTF8.GetBytes("TestMsg");
    var hash = hasher.ComputeHash(new MemoryStream(testmsg));


    var oid = CryptoConfig.MapNameToOID("SHA512");

    var signedData = rsaProvider.SignHash(hash, oid);
    var isSigned = rsaProvider.VerifyHash(hash, oid, signedData);

    return isSigned;
}

Output:

enter image description here

like image 81
FaizanHussainRabbani Avatar answered Nov 08 '22 01:11

FaizanHussainRabbani