5

Im trying to sign / verify a Json Web Token with Bouncycastle in C#. I've had success with RSXXX and HSXXX but I haven't been able to successfully verify one signed with ES256. I've been using https://kjur.github.io/jsrsasign/tool_jwt.html as my measuring stick and this simple function to verify a generated JWT.

public static bool IsTokenValid(
    string jwtBase, 
    string jwtSignature, 
    string publicKey, 
    string algorithmName)
{
    ISigner signer = SignerUtilities.GetSigner(algorithmName);

    byte[] publicKeyBytes = Convert.FromBase64String(publicKey);
    AsymmetricKeyParameter publicKeyParameters = 
        PublicKeyFactory.CreateKey(publicKeyBytes);

    byte[] signatureBaseBytes = Encoding.UTF8.GetBytes(jwtBase);
    signer.Init(false, publicKeyParameters);
    signer.BlockUpdate(signatureBaseBytes, 0, signatureBaseBytes.Length);

    byte[] signatureBytes = Convert.FromBase64String(
        ToProperBase64String(jwtSignature));
    return signer.VerifySignature(signatureBytes);
}

public static string ToProperBase64String(string instance)
{
    instance = instance.Replace('-', '+').Replace('_', '/').Replace("\r", "");
    while (instance.Length % 4 != 0)
    {
        instance = instance + "=";
    }
    return instance;
}

Here is an example jwt signed with the default private key.

string signatureBase =
"eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2p3dC1pZHAuZXhhbXBsZS5jb20iLCJzdWIiOiJtYWlsdG86bWlrZUBleGFtcGxlLmNvbSIsIm5iZiI6MTQ3OTUzMjM0MSwiZXhwIjoxNDc5NTM1OTQxLCJpYXQiOjE0Nzk1MzIzNDEsImp0aSI6ImlkMTIzNDU2IiwidHlwIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9yZWdpc3RlciIsImF1ZCI6WyJodHRwOi8vZm9vMS5jb20iLCJodHRwOi8vZm9vMi5jb20iXX0";
string signature = "aGHSDpqHqGuG89OJCapCVBYvkpStCra8ZD4py02wGf7dPiC6mEdquE2YEGuYcjMKlNOR_0lwzpuNx0xoSmr81A";
string publicKey = @"-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEoBUyo8CQAFPeYPvv78ylh5MwFZjT
CLQeb042TjiMJxG+9DLFmRSMlBQ9T/RsLLc+PmpB1+7yPAR+oR5gZn3kJQ==
-----END PUBLIC KEY-----
".Replace("-----BEGIN PUBLIC KEY-----", "")
.Replace("\n", "")
.Replace("-----END PUBLIC KEY-----", "");

bool isValid = IsTokenValid(signatureBase, signature, publicKey, "SHA-256withECDSA");
//above evaluates to false

Is there something I am missing here? Alternatively I would be happy with another .NET PCL implementation that can sign and verify a ES256 JWT

0 Answers0