[Fact]
public async Task VerfiyJwtTokenUseJwks()
{ var jwt = @"your jwt token"; var wellKnownAddress = "http://your-openid-host/.well-known/openid-configuration";
var httpClientFactory = this.ServiceProvier.GetRequiredService<IHttpClientFactory>();
var httpClient = httpClientFactory.CreateClient(); var response = await httpClient.GetAsync(wellKnownAddress);
response.EnsureSuccessStatusCode(); var json = await response.Content.ReadAsStringAsync();
var jObj = (JObject)JsonConvert.DeserializeObject(json);
var jwks_uri = jObj["jwks_uri"].ToString();
Console.WriteLine($"Jwks_uri: {jwks_uri}"); var keySet = await httpClient.GetStringAsync(jwks_uri);
Console.WriteLine($"keySets: {keySet}"); var ketSets = (JObject)JsonConvert.DeserializeObject(keySet);
var keys = (JArray)ketSets["keys"]; var jwtArray = jwt.Split('.');
var headerObj = (JObject)JsonConvert.DeserializeObject(DecodeJwtToken(jwtArray[0]));
Console.WriteLine($"Token Header: {headerObj}"); var jwtSign = jwtArray[2]; foreach (var key in keys)
{
var kid = headerObj["kid"];
if (key["kid"].ToString() == kid.ToString())
{
var e = key["e"].ToString();
var n = key["n"].ToString();
using (var rsa = System.Security.Cryptography.RSA.Create())
{
var rsaKeyInfo = new RSAParameters
{
Modulus = DecodeBase64ToByteArray(n),
Exponent = DecodeBase64ToByteArray(e)
}; rsa.ImportParameters(rsaKeyInfo);
var d = $"{jwtArray[0]}.{jwtArray[1]}"; var success = rsa.VerifyData(
Encoding.UTF8.GetBytes(d),
DecodeBase64ToByteArray(jwtSign), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); Console.WriteLine($"verfiy: {success}"); var publicKeyPem = ExportPublicKey(rsa); Console.WriteLine($"PublicKey PEM: \r\n{publicKeyPem}"); } } }
} private string DecodeJwtToken(string base64Token)
{
var bytes = DecodeBase64ToByteArray(base64Token);
var json = Encoding.UTF8.GetString(bytes);
return json;
} private byte[] DecodeBase64ToByteArray(string b64String)
{
var m = (b64String.Length % 4);
if (m > 0)
{
if (m == 2)
{
b64String += "==";
}
else
{
b64String += "=";
}
}
return Convert.FromBase64String(b64String.Replace("-", "+").Replace("_", "/"));
} public static string ExportPublicKey(RSA csp)
{
StringWriter outputStream = new StringWriter();
var parameters = csp.ExportParameters(false);
using (var stream = new MemoryStream())
{
var writer = new BinaryWriter(stream);
writer.Write((byte)0x30); // SEQUENCE
using (var innerStream = new MemoryStream())
{
var innerWriter = new BinaryWriter(innerStream);
innerWriter.Write((byte)0x30); // SEQUENCE
EncodeLength(innerWriter, 13);
innerWriter.Write((byte)0x06); // OBJECT IDENTIFIER
var rsaEncryptionOid = new byte[] { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01 };
EncodeLength(innerWriter, rsaEncryptionOid.Length);
innerWriter.Write(rsaEncryptionOid);
innerWriter.Write((byte)0x05); // NULL
EncodeLength(innerWriter, 0);
innerWriter.Write((byte)0x03); // BIT STRING
using (var bitStringStream = new MemoryStream())
{
var bitStringWriter = new BinaryWriter(bitStringStream);
bitStringWriter.Write((byte)0x00); // # of unused bits
bitStringWriter.Write((byte)0x30); // SEQUENCE
using (var paramsStream = new MemoryStream())
{
var paramsWriter = new BinaryWriter(paramsStream);
EncodeIntegerBigEndian(paramsWriter, parameters.Modulus); // Modulus
EncodeIntegerBigEndian(paramsWriter, parameters.Exponent); // Exponent
var paramsLength = (int)paramsStream.Length;
EncodeLength(bitStringWriter, paramsLength);
bitStringWriter.Write(paramsStream.GetBuffer(), 0, paramsLength);
}
var bitStringLength = (int)bitStringStream.Length;
EncodeLength(innerWriter, bitStringLength);
innerWriter.Write(bitStringStream.GetBuffer(), 0, bitStringLength);
}
var length = (int)innerStream.Length;
EncodeLength(writer, length);
writer.Write(innerStream.GetBuffer(), 0, length);
} var base64 = Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length).ToCharArray();
// WriteLine terminates with \r\n, we want only \n
outputStream.Write("-----BEGIN PUBLIC KEY-----\n");
for (var i = 0; i < base64.Length; i += 64)
{
outputStream.Write(base64, i, Math.Min(64, base64.Length - i));
outputStream.Write("\n");
}
outputStream.Write("-----END PUBLIC KEY-----");
} return outputStream.ToString();
} private static void EncodeLength(BinaryWriter stream, int length)
{
if (length < 0) throw new ArgumentOutOfRangeException("length", "Length must be non-negative");
if (length < 0x80)
{
// Short form
stream.Write((byte)length);
}
else
{
// Long form
var temp = length;
var bytesRequired = 0;
while (temp > 0)
{
temp >>= 8;
bytesRequired++;
}
stream.Write((byte)(bytesRequired | 0x80));
for (var i = bytesRequired - 1; i >= 0; i--)
{
stream.Write((byte)(length >> (8 * i) & 0xff));
}
}
} private static void EncodeIntegerBigEndian(BinaryWriter stream, byte[] value, bool forceUnsigned = true)
{
stream.Write((byte)0x02); // INTEGER
var prefixZeros = 0;
for (var i = 0; i < value.Length; i++)
{
if (value[i] != 0) break;
prefixZeros++;
}
if (value.Length - prefixZeros == 0)
{
EncodeLength(stream, 1);
stream.Write((byte)0);
}
else
{
if (forceUnsigned && value[prefixZeros] > 0x7f)
{
// Add a prefix zero to force unsigned if the MSB is 1
EncodeLength(stream, value.Length - prefixZeros + 1);
stream.Write((byte)0);
}
else
{
EncodeLength(stream, value.Length - prefixZeros);
}
for (var i = prefixZeros; i < value.Length; i++)
{
stream.Write(value[i]);
}
}
}

DotnetCore 使用Jwks验证JwtToken签名的更多相关文章

  1. OpenSSL库验证PKCS7签名

    使用Crypto库签名和验证签名请参考Crypto库实现PKCS7签名与签名验证,可以使用OpenSSL库验证Crypto签名,OpenSSL验证签名可使用简单的代码描述如下: //signature ...

  2. ubuntu16.04 apt-get update出错:由于没有公钥,无法验证下列签名

    问题: W: 校验数字签名时出错.此仓库未被更新,所以仍然使用此前的索引文件.GPG 错误:https://packagecloud.io/github/git-lfs/ubuntu xenial I ...

  3. 由于没有公钥,无法验证下列签名 Ubuntu

    问题:执行 apt-get update 时错误 W: GPG 错误:https://apt.dockerproject.org ubuntu-trusty InRelease: 由于没有公钥,无法验 ...

  4. 树莓派 Learning 002 装机后的必要操作 --- 04 添加软件源 之 添加公钥 --- 解决“由于没有公钥,无法验证下列签名”问题

    树莓派 装机后的必要操作 - 添加软件源 解决 添加公钥 时会遇到的问题 当你添加完Debian的软件源后,在终端中执行sudo apt-get update时,会出现下面的错误:(这里我添加了3个软 ...

  5. sudo apt-get update 没有公钥,无法验证下列签名

    在更新系统源后,输入sudo apt-get update之后出现提示: W: GPG 错误:http://archive.ubuntukylin.com:10006 xenial InRelease ...

  6. ”W: GPG 错误:http://ppa.launchpad.net lucid Release: 由于没有公钥,无法验证下列签名:“的问题

    在安装更新时,即在运行,命令行sudo apt-get update 或者运行更新管理器的时候,出现如下错误: W: GPG 错误:http://ppa.launchpad.net lucid Rel ...

  7. 更新linux时候提示“由于没有公钥,无法验证下列签名".

    本文链接:https://blog.csdn.net/loovejava/article/details/21837935 新安装的Ubuntu在使用sudo apt-get update更新源码的时 ...

  8. 乌班图14更新软件提示错误:https://mirrors.aliyun.com kubernetes-xenial InRelease: 由于没有公钥,无法验证下列签名: NO_PUBKEY 6A030B21BA07F4FB

    提示如下 获取: https://mirrors.aliyun.com kubernetes-xenial InRelease 忽略 https://mirrors.aliyun.com kubern ...

  9. .net mvc 微信公众号 验证微信签名

    官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421135319&token=&lang=zh_CN ...

随机推荐

  1. Android数据存储之共享参数SharedPreferences

    SharedPreferences是Android的一个轻量级存储工具,采用的存储结构是Key-Value的键值对方式,类似于Java的Properties类,二者都是把Key-Value的键值对保存 ...

  2. Chocolaty

    原文是用markdown格式写的,稍微改了下发了博客,格式可能会很奇怪.. Chocolaty官网 Chocolaty是一款Windows平台的包管理工具,类似于centos的yum或ubuntu的a ...

  3. 图像读取函数cv::imread()的几种使用方式

    string imgpath = "C:\Users\Y\Pictures\miao.jpg"; OpenCV的imread()函数不支持单右斜线形式的路径,即不支持上述形式的路径 ...

  4. C++使用taskkill 命令强制结束进程

    一:查看 taskkill 命令和参数的方法 window系统下,快捷键win + R 打开运行 ,输入cmd回车,在 cmd 里面输入: taskkill /?  二:语法: taskkill [/ ...

  5. 03-SV过程语句和子程序

    1.过程语句 for语句.do-while语句.while语句 initial begin string cmd; int file,c; $display("=========== con ...

  6. 为什么要使用Redis? —— Redis实战经验

    (序言,从一张思维导图开始,慢慢介绍我自己关于Redis的实战经验) 现在很多互联网应用的服务端都使用到了Redis,到底大家为什么要用Redis呢?Redis有很多特性,比如高性能.高可用.数据类型 ...

  7. oracle建数据库

    oracle用户界面登陆 用户要切换到oracle sqlplus / as sysdba //sys用户是oracle的最高管理员所以要加上as help index //查看命令列表,sql中不区 ...

  8. py二级习题

    题目:使用turtle库的turtle.forward(),turtle.left(),函数绘制一个六边形,边长为100 像素 import turtle for i in range(6): tur ...

  9. javaWeb快速入门+——初体验-HelloWorld

    文章转载自 https://www.cnblogs.com/1906859953Lucas/p/10821840.html 练习成品下载 https://www.lanzous.com/i9fljkj ...

  10. vim编辑器-删除命令

    dd:删除游标所在的一整行(常用)   ndd:n为数字.删除光标所在的向下n行,例如20dd则是删除光标所在的向下20行   d1G:删除光标所在到第一行的所有数据   dG:删除光标所在到最后一行 ...