Skip to content

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

@ArsenAblaev

Description

@ArsenAblaev

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);
        }
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions