我试图用C#中的Bouncycastle签署/验证Json Web令牌。我在RSXXX和HSXXX上取得了成功,但我还没能成功验证用ES256签名的用户。我一直在使用https://kjur.github.io/jsrsasign/tool_jwt.html作为我的测量棒和这个简单的函数来验证生成的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;
}
以下是使用默认私钥签名的jwt示例。
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
我在这里缺少什么吗?或者,我会对另一个可以签署和验证ES256 JWT的.NET PCL实现感到满意