如何使用我自己的 rsa 私钥使用 rs256 算法对字节进行签名?

时间:2023-03-29
本文介绍了如何使用我自己的 rsa 私钥使用 rs256 算法对字节进行签名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有自己的私钥字符串,即

I have my own private key string, i.e.

-----BEGIN RSA PRIVATE KEY-----

MIICXAIBAAKBgQCSAYYgzvGTww....
....
....
.....
3yUMYj9oYzqdrRHP0XgD0cEEvyqPBwLaNsRdFwy5qTiHjj0f+ZWHQWmqcoLmmpzyZEbIvQm/VhbjRF6iKG4WZ9Hfa7ntYRNGdWgD/KMIeZI=

-----END RSA PRIVATE KEY-----

现在,我需要在 C# 中使用此私钥签署我的声明集以生成 JWT 有效负载.

Now, I need to sign my claim set using this private key in C# to generate JWT payload.

我写了以下代码:

var utc0 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var issueTime = DateTime.Now;

var iat = (int)issueTime.Subtract(utc0).TotalSeconds;
var exp = (int)issueTime.AddMinutes(55).Subtract(utc0).TotalSeconds;

var payload = new
{
    iss = email,
    prn = prn,
    scope = "scope",
    aud = "https://example.com",
    exp = exp,
    iat = iat
};

var segments = new List<string>();
var header = new { typ = "JWT", alg = "RS256" };

byte[] headerBytes = Encoding.UTF8.GetBytes(jsonSerializer.Serialize(header));
byte[] payloadBytes = Encoding.UTF8.GetBytes(jsonSerializer.Serialize(payload));

segments.Add(Base64UrlEncode(headerBytes));
segments.Add(Base64UrlEncode(payloadBytes));

var stringToSign = string.Join(".", segments.ToArray());

var bytesToSign = Encoding.UTF8.GetBytes(stringToSign);

现在我需要这些 bytesToSign 由我的私钥签名,正如我上面提到的使用 rs256 算法.任何人都可以帮忙吗?

Now I need these bytesToSign to be signed by my private key as I mentioned above using the rs256 alogorithm. Can anyone help?

我已按照以下内容更新了我的代码:

I've updated my code as per the following:

var pemprivatekey = OpenSSLKey.DecodeOpenSSLPrivateKey(privateKey);
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();

if (pemprivatekey != null)
{
    rsaProvider = OpenSSLKey.DecodeRSAPrivateKey(pemprivatekey);
}

byte[] signature = rsaProvider.SignData(bytesToSign, "SHA256");

segments.Add(Base64UrlEncode(signature));

return string.Join(".", segments.ToArray());

并生成 JWT 令牌.请让我知道我在哪里犯了错误,因为它不正确:当我将它传递给 API 时,它不起作用并引发错误.

and generated JWT token. Please let me know where I made a mistake as its not correct one: when I pass it to the API, it doesn't work and throws an error.

推荐答案

我找到了一些纯粹基于 Javascript 的解决方案,如果它对任何人有用的话.您可以在这里找到 JS 库.

I found some purely Javascript based solution, if it is useful to anyone. You can find the JS Libraries here.

它解决了我的要求.

这篇关于如何使用我自己的 rsa 私钥使用 rs256 算法对字节进行签名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:在 ASP.NET Core 的 Swagger 中使用 JWT(授权:Bearer) 下一篇:验证 Google OpenID Connect JWT ID 令牌

相关文章