67 lines
2.6 KiB
C#
67 lines
2.6 KiB
C#
|
|
using LMS.Common.RSAKey;
|
|
using LMS.DAO;
|
|
using LMS.Repository.DB;
|
|
using LMS.Tools.Extensions;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace LMS.service.Configuration
|
|
{
|
|
public class RsaConfigurattions(IServiceProvider serviceProvider) : IHostedService
|
|
{
|
|
private readonly IServiceProvider _serviceProvider = serviceProvider;
|
|
|
|
public async Task StartAsync(CancellationToken cancellationToken)
|
|
{
|
|
using var scope = _serviceProvider.CreateScope();
|
|
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
|
using var transaction = await dbContext.Database.BeginTransactionAsync(cancellationToken);
|
|
try
|
|
{
|
|
int count = await dbContext.RsaKeys.CountAsync(cancellationToken: cancellationToken);
|
|
|
|
// 先删除无效的RSA数据
|
|
List<RsaKeys> rsaKeys = await dbContext.RsaKeys.Where(x => x.UseCount > 50 || x.ExpirationTime < BeijingTimeExtension.GetBeijingTime()).ToListAsync(cancellationToken: cancellationToken);
|
|
if (rsaKeys.Count > 0)
|
|
{
|
|
dbContext.RsaKeys.RemoveRange(rsaKeys);
|
|
}
|
|
|
|
// 新增 保证数据库中有指定数量的RSA数据
|
|
|
|
int AddCount = 20 - (count - rsaKeys.Count);
|
|
for (int i = 0; i < AddCount; i++)
|
|
{
|
|
RSAKeyGenerateModel rSAKeyGenerate = RsaKeyPairGenerator.InitRsaKey();
|
|
|
|
await dbContext.RsaKeys.AddAsync(new RsaKeys
|
|
{
|
|
PublicKey = rSAKeyGenerate.PublicKey,
|
|
EncryptedPrivateKey = rSAKeyGenerate.EncryptedPrivateKey,
|
|
EncryptionKey = rSAKeyGenerate.EncryptedKey,
|
|
EncryptionIV = rSAKeyGenerate.EncryptionIV,
|
|
UseCount = 0,
|
|
ExpirationTime = BeijingTimeExtension.GetBeijingTime().AddDays(10),
|
|
Id = Guid.NewGuid().ToString(),
|
|
}, cancellationToken);
|
|
}
|
|
|
|
await dbContext.SaveChangesAsync(cancellationToken);
|
|
await transaction.CommitAsync(cancellationToken);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
await transaction.RollbackAsync(cancellationToken);
|
|
// 根据需要处理异常,例如终止应用程序
|
|
Console.WriteLine(ex.Message);
|
|
Environment.Exit(1);
|
|
}
|
|
}
|
|
|
|
public Task StopAsync(CancellationToken cancellationToken)
|
|
{
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|
|
}
|