问题描述
我有我自己的私人密钥字符串,即
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算法FFT提到要由我的私钥签名。任何人都可以帮忙吗?
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算法签个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!