我们如何在c#中创建AsymmetricSecurityKey。实际上我们正在使用AsymetricSecurityKey创建签名凭据,这里是我们的代码:
// Define const Key this should be private secret key stored in some safe place
string key = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";
// Create Security key using private key above:
// not that latest version of JWT using Microsoft namespace instead of System
var securityKey = new AsymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
// Also note that securityKey length should be >256b
// so you have to make sure that your private key has a proper length
//
var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials
(securityKey, SecurityAlgorithms.HmacSha256Signature);
答案 0 :(得分:1)
您可以使用以下方式生成公钥/私钥:
public void GenerateRsaCryptoServiceProviderKey()
{
var rsaProvider = new RSACryptoServiceProvider(512);
SecurityKey key = new RsaSecurityKey(rsaProvider);
}
您应该使用以下RsaSha256
:
var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials
(key, SecurityAlgorithms.RsaSha256);
答案 1 :(得分:0)
您是否正在专门寻找AsymmetricSecurityKey
?
我注意到您正在引用HM256算法。这使我相信您正在寻找SymmetricSecurityKey
。另外,您的方法似乎非常适用于使用HMAC alg。
要生成SymmetricSecurityKey
,您可以尝试使用以下代码:
// Define const Key this should be private secret key stored in some safe place
string key = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";
// Create Security key using private key above:
// not that latest version of JWT using Microsoft namespace instead of System
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
// Also note that securityKey length should be >256b
// so you have to make sure that your private key has a proper length
//
var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
如果您想要使用RS256 alg(它将使用pfx格式的证书)的解决方案,可以发表评论,我也会尽力为您提供示例。
答案 2 :(得分:0)
这将从F#中的RSA公钥创建安全密钥。
let pem = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnzyis1ZjfNB0bBgKFMSvvkTtwlvBsaJq7S5wA+kzeVOVpVWwkWdVha4s38XM/pa/yr47av7+z3VTmvDRyAHcaT92whREFpLv9cj5lTeJSibyr/Mrm/YtjCZVWgaOYIhwrXwKLqPr/11inWsAkfIytvHWTxZYEcXLgAXFuUuaS3uF9gEiNQwzGTU1v0FqkqTBr4B8nW3HCN47XUu0t8Y0e+lf4s4OxQawWD79J9/5d3Ry0vbV3Am1FtGJiJvOwRsIfVChDpYStTcHTCMqtvWbV6L11BWkpzGXSW4Hv43qa+GSYOD2QU68Mb59oSk2OB+BtOLpJofmbGEGgvmwyCI9MwIDAQAB"
let getPublicKey (pem: string) =
let publicKey = ReadOnlySpan<byte>(Convert.FromBase64String(pem))
let rsa = RSA.Create()
let mutable read = 0
rsa.ImportSubjectPublicKeyInfo(publicKey, &read)
new RsaSecurityKey(rsa)
getPublicKey pem