33 lines
1.1 KiB
C#
33 lines
1.1 KiB
C#
using Microsoft.IdentityModel.Tokens;
|
|||
|
|
|
||
|
|
using MongoDB.Entities;
|
||
|
|
|
||
|
|
using System.Security.Cryptography;
|
||
|
|
|
||
|
|
namespace PrivaPub.Api.Mastodon.Auth
|
||
|
|
{
|
||
|
|
public class OidcKey : Entity
|
||
|
|
{
|
||
|
|
public string Use { get; set; }
|
||
|
|
public string PrivateKeyPem { get; set; }
|
||
|
|
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||
|
|
|
||
|
|
public const string Signing = "signing";
|
||
|
|
public const string Encryption = "encryption";
|
||
|
|
|
||
|
|
public static RsaSecurityKey Load(string use)
|
||
|
|
{
|
||
|
|
var key = DB.Default.Find<OidcKey>().Match(k => k.Use == use).Sort(k => k.CreatedAt, Order.Ascending).ExecuteFirstAsync().GetAwaiter().GetResult();
|
||
|
|
if (key == default)
|
||
|
|
{
|
||
|
|
using var created = RSA.Create(2048);
|
||
|
|
key = new OidcKey { Use = use, PrivateKeyPem = created.ExportRSAPrivateKeyPem() };
|
||
|
|
DB.Default.SaveAsync(key).GetAwaiter().GetResult();
|
||
|
|
key = DB.Default.Find<OidcKey>().Match(k => k.Use == use).Sort(k => k.CreatedAt, Order.Ascending).ExecuteFirstAsync().GetAwaiter().GetResult();
|
||
|
|
}
|
||
|
|
var rsa = RSA.Create();
|
||
|
|
rsa.ImportFromPem(key.PrivateKeyPem);
|
||
|
|
return new RsaSecurityKey(rsa) { KeyId = key.ID };
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|