关于JWT中RSA数据加密协议在.net中应用
加密协议有哪些
加密协议分为对称加密和非对称加密。
对称加密就是将信息使用一个密钥进行加密,解密时使用同样的密钥,同样的算法进行解密。
非对称加密,又称公开密钥加密,是加密和解密使用不同密钥的算法,广泛用于信息传输中。
对称加密协议
AES、DES、RC5、RC6等
非对称加密协议
RSA、DSA等
RSA数据加密协议是什么
RSA加密算法是一种非对称加密算法,在公开密钥加密和电子商业中被广泛使用。RSA是由罗纳德·李维斯特(Ron Rivest)、阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)在1977年一起提出的。当时他们三人都在麻省理工学院工作。RSA 就是他们三人姓氏开头字母拼在一起组成的。
RSA加密协议的原理
对极大整数做因数分解。可以在不直接传递密钥的情况下完成解密。可以确保信息的安全性,避免了直接传递密钥所造成的被破解的风险,RSA是由一对密钥来进行加解密的过程,分别称为公钥和私钥.
RSA格式
通常PKCS1密钥对的开始部分为:
-----BEGIN RSA PRIVATE KEY-----或
-----BEGIN RSA PUBLIC KEY-----
而PKCS8密钥对的开始部分为:
-----BEGIN PRIVATE KEY----- 或
-----BEGIN ENCRYPTED PRIVATE KEY----- 或
-----BEGIN PUBLIC KEY-----
这种包含开头和结尾标记的是PEM密钥格式,但在.net中只支持XML格式,可以通过第三方库BouncyCastle,将PEM和XML格式互转
RSA密钥的生成
密钥可以在线生成,推荐选择密钥长度大于等于2024位,因为目前已经破解了接近1024位了。格式选择PKCS1。
在.Net中的应用
.Net中应用
生成私钥RSA对象
点击查看代码
var PrivateKey =@"
-----BEGIN RSA PRIVATE KEY-----
...................................
-----END RSA PRIVATE KEY-----
";
//生成RSA私钥对象
var rsa = RSA.Create();
var xmlPriKey = PemPrivateKey(PrivateKey);
rsa.ImportParameters(xmlPriKey);
SecurityKey key2 = new RsaSecurityKey(rsa);
//生成JWT密钥,授权
var token = new JwtSecurityToken(
issuer: "GATE",
audience: "API",
expires: exPriseDateTime,
notBefore: DateTime.Now,
claims: claims,
signingCredentials: new SigningCredentials(key2, SecurityAlgorithms.RsaSha256)
);
var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
return jwtToken;
static RSAParameters PemPrivateKey(string pemPrivateKeyStr)
{
RsaPrivateCrtKeyParameters pemPrivateKey;
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(pemPrivateKeyStr)))
{
using (var sr = new StreamReader(ms))
{
//在.net中只支持XML格式的RSA密钥,所以需要借助第三方库才能识别PEM格式的密钥
var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(sr);
var keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
pemPrivateKey = (RsaPrivateCrtKeyParameters)keyPair.Private;
}
}
var p = new RSAParameters
{
Modulus = pemPrivateKey.Modulus.ToByteArrayUnsigned(),
Exponent = pemPrivateKey.PublicExponent.ToByteArrayUnsigned(),
D = pemPrivateKey.Exponent.ToByteArrayUnsigned(),
P = pemPrivateKey.P.ToByteArrayUnsigned(),
Q = pemPrivateKey.Q.ToByteArrayUnsigned(),
DP = pemPrivateKey.DP.ToByteArrayUnsigned(),
DQ = pemPrivateKey.DQ.ToByteArrayUnsigned(),
InverseQ = pemPrivateKey.QInv.ToByteArrayUnsigned(),
};
return p;
}
.Net Core中应用
生成私钥RSA对象
点击查看代码
var Jwt:Prikey = "去掉开头和结束的标记,以及换行和空格符".replace("\r","").replace("\n","").replace(" ","").replace("BEGIN RSA PRIVATE KEY","").replace("END RSA PRIVATE KEY","");
[AllowAnonymous]
public Task<string> GetToken()
{
var configurationBuilder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
var configuration = configurationBuilder.Build();
List<Claim> claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "name"));
claims.Add(new Claim("ID", "123456"));
//生成RSA私钥实例
var rsa = RSA.Create();
//在.net core中原生支持PEM格式的密钥 ,ImportRSAPrivateKey 导入私钥
rsa.ImportRSAPrivateKey(Convert.FromBase64String(configuration.GetSection("Jwt:Prikey").Value), out _);
SecurityKey key2 = new RsaSecurityKey(rsa);
var token = new JwtSecurityToken(
issuer: configuration.GetSection("Jwt:Issuer").Value,
audience: configuration.GetSection("Jwt:Audience").Value,
expires: DateTime.Now.AddDays(1),
notBefore: DateTime.Now,
claims: claims,
signingCredentials: new SigningCredentials(key2, SecurityAlgorithms.RsaSha256)
);
var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
return Task.FromResult(jwtToken);
}
生成公钥RSA对象
点击查看代码
public void ConfigureServices(IServiceCollection services)
{
.......................
var configurationBuilder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
var configuration = configurationBuilder.Build();
var rsa = RSA.Create();
var pubkey = File.ReadAllText("Public.key").Replace("-----BEGIN RSA PUBLIC KEY-----", "").Replace("-----END RSA PUBLIC KEY-----", "").Replace("\r", "").Replace("\n", "").Replace(" ", "");
//ImportRSAPublicKey 导入公钥
rsa.ImportRSAPublicKey(Convert.FromBase64String(pubkey), out _);
SecurityKey key2 = new RsaSecurityKey(rsa);
services.AddAuthorization(options =>
{
}).AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidAudience = configuration.GetSection("Jwt:Audience").Value,
ValidIssuer = configuration.GetSection("Jwt:Issuer").Value,
IssuerSigningKey = key2
};
});
.......................
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
.......................
app.UseAuthentication();
app.UseAuthorization();
.......................
}