如何使用 PEM 密钥在 C# 中签名/加密 JWT? [英] How to sign/encrypt JWT in C# with PEM key?

查看:60
本文介绍了如何使用 PEM 密钥在 C# 中签名/加密 JWT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建需要使用 Google 提供的密钥进行签名的自定义令牌.密钥以文本形式提供,例如 -----BEGIN PRIVATE KEY-----\nMIIE....

I need to create custom tokens that need to be signed using a key provided by Google. The key is provided as text, like -----BEGIN PRIVATE KEY-----\nMIIE....

我通过使用 BouncyCastle 读取 PEM 密钥并获取 RSA 密钥来完成这项工作,但现在我需要这个项目在 Linux 下运行,所以我不能使用 BouncyCastle,因为它只能在 Windows 下工作(它使用 RSACryptoServiceProvider).

I had this working by using BouncyCastle to read the PEM key and get the RSA keys, but now I need this project to run under Linux so I can't use BouncyCastle as it only works under Windows (it makes uses of RSACryptoServiceProvider).

那么,有没有一种方法可以实现相同的结果,但只使用 .NET Standard 代码?

So, is there a way I can achieve the same result but using only .NET Standard code?

我已经尝试将 PEM 文件转换为 PFX 文件,但我没有任何证书.尝试从此处here 不起作用(OpenSSL 说证书不属于密钥提供).

I already tried to convert the PEM file to a PFX file, but I don't have any certificates. Tried to get the certificates from here or here didn't work (OpenSSL says that the certificates don't belong to the key provided).

推荐答案

您可以将 PEM 文件转换为 p12 文件并使用该 p12 对您的 JWT 进行签名

You can convert your PEM file to p12 file and signed your JWT with that p12

var payload = new Dictionary<string, object>()
{
    { "sub", "mr.x@contoso.com" },
    { "exp", 1300819380 }
};

var privateKey=new X509Certificate2("my-key.p12", "password").GetRSAPrivateKey();

string token=Jose.JWT.Encode(payload, privateKey, JwsAlgorithm.RS256);

这里是详细链接https://github.com/dvsekhvalnov/jose-jwt#rs--and-ps--family

这篇关于如何使用 PEM 密钥在 C# 中签名/加密 JWT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆