Yodlee/jwt

failed to construct sequence from byte[]: DER length more than 4 bytes

Opened this issue · 0 comments

Hello! I created privateKey.key file with following body.

-----BEGIN PRIVATE KEY-----{Private Key body}-----END PRIVATE KEY-----

But once I try to create JWT token I got the following error in line var obj = pemReader.ReadObject()

PemException: problem creating private key: System.ArgumentException: failed to construct sequence from byte[]: DER length more than 4 bytes: 83 at Org.BouncyCastle.Asn1.Asn1Sequence.GetInstance(Object obj) at Org.BouncyCastle.OpenSsl.PemReader.ReadPrivateKey(PemObject pemObject)

This is my code:

   public static string CreateToken(string keyPath, string issuerId, string username = null)
    {
        var currentTime = DateTimeOffset.Now.ToUnixTimeSeconds();

        var payload = new Dictionary<string, object>
        {
            ["iss"] = issuerId, ["iat"] = currentTime, ["exp"] = currentTime + 1800
        };

        if (username != null)
            payload["sub"] = username;

        return CreateToken(payload, new FileInfo(keyPath));
    }

    private static string CreateToken(Dictionary<string, object> payload, FileInfo privateKey)
    {
        RSAParameters rsaParams;

        using (var streamReader = privateKey.OpenText())
        {
            var pemReader = new PemReader(streamReader);

            RsaPrivateCrtKeyParameters privkey = null;
            var obj = pemReader.ReadObject();

            if (obj != null)
                privkey = (RsaPrivateCrtKeyParameters) obj;

            rsaParams = DotNetUtilities.ToRSAParameters(privkey);
        }

        using (var rsa = new RSACryptoServiceProvider())
        {
            rsa.ImportParameters(rsaParams);

            return Jose.JWT.Encode(payload, rsa, Jose.JwsAlgorithm.RS512);
        }
    }