Compare commits
12 Commits
144fe86987
...
a94c7249e4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a94c7249e4 | ||
|
|
3f8145e6dc | ||
|
|
f3f65415e1 | ||
|
|
192a93d153 | ||
|
|
9ec9bcd474 | ||
|
|
7dd8271f4a | ||
|
|
b8de148c52 | ||
|
|
0523308083 | ||
|
|
875692b578 | ||
|
|
973a5f1023 | ||
|
|
8498dc0456 | ||
|
|
6a12ad77ec |
@@ -0,0 +1,23 @@
|
||||
namespace DigitalData.Core.Abstractions.Security.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a unique security context that identifies an issuer and an audience.
|
||||
/// </summary>
|
||||
public interface IUniqueSecurityContext
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the issuer identifier for this security context.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The issuer typically represents the entity that issues a token or a cryptographic key.
|
||||
/// </remarks>
|
||||
string Issuer { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the audience identifier for this security context.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The audience typically represents the intended recipient or target of a token or cryptographic operation.
|
||||
/// </remarks>
|
||||
string Audience { get; }
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>net7.0;net8.0</TargetFrameworks>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<PackageId>DigitalData.Core.Abstractions.Security</PackageId>
|
||||
<Version>1.0.0</Version>
|
||||
<AssemblyVersion>1.0.0</AssemblyVersion>
|
||||
<FileVersion>1.0.0</FileVersion>
|
||||
<Authors>Digital Data GmbH</Authors>
|
||||
<Company>Digital Data GmbH</Company>
|
||||
<Product>Digital Data GmbH</Product>
|
||||
<Copyright>Copyright 2025</Copyright>
|
||||
<PackageProjectUrl>http://git.dd:3000/AppStd/WebCoreModules.git</PackageProjectUrl>
|
||||
<PackageIcon>core_icon.png</PackageIcon>
|
||||
<Description>This package defines the foundational abstractions for implementing security functionalities within the DigitalData.Core ecosystem. It provides interfaces and base classes for encryption, decryption, and secure authentication mechanisms. Designed to ensure flexibility and consistency, it enables seamless integration with various security implementations, such as RSA-based encryption and JWT handling.</Description>
|
||||
<PackageTags>digital data core security abstractions</PackageTags>
|
||||
<RepositoryUrl>http://git.dd:3000/AppStd/WebCoreModules.git</RepositoryUrl>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="..\..\nuget-package-icons\core_icon.png">
|
||||
<Pack>True</Pack>
|
||||
<PackagePath>\</PackagePath>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.7.1" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,64 @@
|
||||
using DigitalData.Core.Abstractions.Security.Common;
|
||||
using DigitalData.Core.Abstractions.Security.Key;
|
||||
using DigitalData.Core.Abstractions.Security.Services;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Text;
|
||||
|
||||
namespace DigitalData.Core.Abstractions.Security.Extensions;
|
||||
|
||||
public static class SecurityExtensions
|
||||
{
|
||||
#region Unique Security Context
|
||||
public static IEnumerable<TUniqueSecurityContext> GetByIssuer<TUniqueSecurityContext>(this IEnumerable<TUniqueSecurityContext> contextes, string issuer) where TUniqueSecurityContext : IUniqueSecurityContext
|
||||
=> contextes.Where(c => c.Issuer == issuer);
|
||||
|
||||
public static IEnumerable<TUniqueSecurityContext> GetByAudience<TUniqueSecurityContext>(this IEnumerable<TUniqueSecurityContext> contextes, string audience) where TUniqueSecurityContext : IUniqueSecurityContext
|
||||
=> contextes.Where(c => c.Audience == audience);
|
||||
|
||||
public static TUniqueSecurityContext Get<TUniqueSecurityContext>(this IEnumerable<TUniqueSecurityContext> contextes, string issuer, string audience) where TUniqueSecurityContext : IUniqueSecurityContext
|
||||
=> contextes.Where(c => c.Issuer == issuer && c.Audience == audience).SingleOrDefault()
|
||||
?? throw new InvalidOperationException($"Exactly one {typeof(TUniqueSecurityContext).Name} must exist with Issuer: '{issuer}' and Audience: '{audience}'.");
|
||||
|
||||
public static bool TryGet<TUniqueSecurityContext>(this IEnumerable<TUniqueSecurityContext> contextes, string issuer, string audience, out TUniqueSecurityContext context) where TUniqueSecurityContext : IUniqueSecurityContext
|
||||
{
|
||||
#pragma warning disable CS8601 // Possible null reference assignment.
|
||||
context = contextes.SingleOrDefault(c => c.Issuer == issuer && c.Audience == audience);
|
||||
#pragma warning restore CS8601 // Possible null reference assignment.
|
||||
return context is not null;
|
||||
}
|
||||
|
||||
public static TUniqueSecurityContext Match<TUniqueSecurityContext>(this IEnumerable<TUniqueSecurityContext> contextes, IUniqueSecurityContext lookupContext) where TUniqueSecurityContext : IUniqueSecurityContext
|
||||
=> contextes.Get(lookupContext.Issuer, lookupContext.Audience);
|
||||
|
||||
public static bool TryMatch<TUniqueSecurityContext>(this IEnumerable<TUniqueSecurityContext> contextes, IUniqueSecurityContext lookupContext, out TUniqueSecurityContext context) where TUniqueSecurityContext : IUniqueSecurityContext
|
||||
=> contextes.TryGet(lookupContext.Issuer, lookupContext.Audience, out context);
|
||||
#endregion Unique Security Context
|
||||
|
||||
#region De/serilization
|
||||
internal static byte[] Base64ToByte(this string base64String) => Convert.FromBase64String(base64String);
|
||||
|
||||
internal static string BytesToString(this byte[] bytes) => Encoding.UTF8.GetString(bytes);
|
||||
|
||||
internal static string ToBase64String(this byte[] bytes) => Convert.ToBase64String(bytes);
|
||||
|
||||
internal static byte[] ToBytes(this string str) => Encoding.UTF8.GetBytes(str);
|
||||
|
||||
public static string Decrypt(this IAsymmetricDecryptor decryptor, string data) => decryptor
|
||||
.Decrypt(data.Base64ToByte()).BytesToString();
|
||||
#endregion De/serilization
|
||||
|
||||
#region Asymmetric Encryptor
|
||||
public static string Encrypt(this IAsymmetricEncryptor encryptor, string data) => encryptor.Encrypt(data.ToBytes()).ToBase64String();
|
||||
#endregion Asymmetric Encryptor
|
||||
|
||||
#region Jwt Signature Handler
|
||||
public static string WriteToken<TPrincipal>(this IJwtSignatureHandler<TPrincipal> handler, SecurityTokenDescriptor descriptor)
|
||||
=> handler.WriteToken(handler.CreateToken(descriptor));
|
||||
|
||||
public static string WriteToken<TPrincipal>(this IJwtSignatureHandler<TPrincipal> handler, TPrincipal subject, IAsymmetricTokenDescriptor descriptor)
|
||||
=> handler.WriteToken(handler.CreateToken(subject: subject, descriptor: descriptor));
|
||||
|
||||
public static string WriteToken<TPrincipal>(this IJwtSignatureHandler<TPrincipal> handler, TPrincipal subject, string issuer, string audience)
|
||||
=> handler.WriteToken(handler.CreateToken(subject: subject, issuer: issuer, audience: audience));
|
||||
#endregion Jwt Signature Handler
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace DigitalData.Core.Abstractions.Security.Key;
|
||||
|
||||
public interface IAsymmetricDecryptor : IAsymmetricPrivateKey
|
||||
{
|
||||
byte[] Decrypt(byte[] data);
|
||||
|
||||
IAsymmetricEncryptor Encryptor { get; }
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace DigitalData.Core.Abstractions.Security.Key;
|
||||
|
||||
public interface IAsymmetricEncryptor : IAsymmetricPublicKey
|
||||
{
|
||||
byte[] Encrypt(byte[] data);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace DigitalData.Core.Abstractions.Security.Key;
|
||||
|
||||
public interface IAsymmetricKey
|
||||
{
|
||||
string? Id { get; }
|
||||
|
||||
string Content { get; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace DigitalData.Core.Abstractions.Security.Key;
|
||||
|
||||
public interface IAsymmetricPrivateKey : IAsymmetricKey
|
||||
{
|
||||
bool IsEncrypted { get; }
|
||||
|
||||
IAsymmetricPublicKey PublicKey { get; }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
namespace DigitalData.Core.Abstractions.Security.Key;
|
||||
|
||||
public interface IAsymmetricPublicKey : IAsymmetricKey
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
using DigitalData.Core.Abstractions.Security.Common;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace DigitalData.Core.Abstractions.Security.Key;
|
||||
|
||||
/// <summary>
|
||||
/// Contains some information which used to create a security token. Designed to abstract <see cref="SecurityTokenDescriptor"/>
|
||||
/// </summary>
|
||||
public interface IAsymmetricTokenDescriptor : IAsymmetricPrivateKey, IUniqueSecurityContext
|
||||
{
|
||||
IAsymmetricTokenValidator Validator { get; }
|
||||
|
||||
TimeSpan Lifetime { get; init; }
|
||||
|
||||
#region SecurityTokenDescriptor Map
|
||||
/// <summary>
|
||||
/// Defines the compression algorithm that will be used to compress the JWT token payload.
|
||||
/// </summary>
|
||||
string CompressionAlgorithm { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="EncryptingCredentials"/> used to create a encrypted security token.
|
||||
/// </summary>
|
||||
EncryptingCredentials EncryptingCredentials { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the value of the 'expiration' claim. This value should be in UTC.
|
||||
/// </summary>
|
||||
DateTime? Expires { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time the security token was issued. This value should be in UTC.
|
||||
/// </summary>
|
||||
DateTime? IssuedAt { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the notbefore time for the security token. This value should be in UTC.
|
||||
/// </summary>
|
||||
DateTime? NotBefore { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the token type.
|
||||
/// <remarks> If provided, this will be added as the value for the 'typ' header parameter. In the case of a JWE, this will be added to both the inner (JWS) and the outer token (JWE) header. By default, the value used is 'JWT'.
|
||||
/// If <see cref="AdditionalHeaderClaims"/> also contains 'typ' header claim value, it will override the TokenType provided here.
|
||||
/// This value is used only for JWT tokens and not for SAML/SAML2 tokens</remarks>
|
||||
/// </summary>
|
||||
string TokenType { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="Dictionary{TKey, TValue}"/> which contains any custom header claims that need to be added to the JWT token header.
|
||||
/// The 'alg', 'kid', 'x5t', 'enc', and 'zip' claims are added by default based on the <see cref="SigningCredentials"/>,
|
||||
/// <see cref="EncryptingCredentials"/>, and/or <see cref="CompressionAlgorithm"/> provided and SHOULD NOT be included in this dictionary as this
|
||||
/// will result in an exception being thrown.
|
||||
/// <remarks> These claims are only added to the outer header (in case of a JWE).</remarks>
|
||||
/// </summary>
|
||||
IDictionary<string, object> AdditionalHeaderClaims { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="Dictionary{TKey, TValue}"/> which contains any custom header claims that need to be added to the inner JWT token header.
|
||||
/// The 'alg', 'kid', 'x5t', 'enc', and 'zip' claims are added by default based on the <see cref="SigningCredentials"/>,
|
||||
/// <see cref="EncryptingCredentials"/>, and/or <see cref="CompressionAlgorithm"/> provided and SHOULD NOT be included in this dictionary as this
|
||||
/// will result in an exception being thrown.
|
||||
/// <remarks>
|
||||
/// For JsonWebTokenHandler, these claims are merged with <see cref="AdditionalHeaderClaims"/> while adding to the inner JWT header.
|
||||
/// </remarks>
|
||||
/// </summary>
|
||||
IDictionary<string, object> AdditionalInnerHeaderClaims { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="SigningCredentials"/> used to create a security token.
|
||||
/// </summary>
|
||||
SigningCredentials SigningCredentials { get; }
|
||||
#endregion SecurityTokenDescriptor
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace DigitalData.Core.Abstractions.Security.Key;
|
||||
|
||||
public interface IAsymmetricTokenValidator : IAsymmetricPublicKey
|
||||
{
|
||||
SecurityKey SecurityKey { get; }
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using System.Security.Cryptography;
|
||||
using DigitalData.Core.Abstractions.Security.Key;
|
||||
|
||||
namespace DigitalData.Core.Abstractions.Security.Services;
|
||||
|
||||
public interface IAsymmetricKeyFactory
|
||||
{
|
||||
string CreatePrivateKeyPem(int? keySizeInBits = null, bool encrypt = false);
|
||||
|
||||
string CreateEncryptedPrivateKeyPem(
|
||||
PbeEncryptionAlgorithm? pbeEncryptionAlgorithm = null,
|
||||
HashAlgorithmName? hashAlgorithmName = null,
|
||||
int? iterationCount = null,
|
||||
int? keySizeInBits = null,
|
||||
string? password = null);
|
||||
|
||||
string CreateEncryptedPrivateKeyPem(
|
||||
PbeParameters pbeParameters,
|
||||
int? keySizeInBits = null,
|
||||
string? password = null);
|
||||
|
||||
IAsymmetricDecryptor CreateDecryptor(string pem, string? issuer = null, string? audience = null, bool encrypt = false, RSAEncryptionPadding? padding = null);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using DigitalData.Core.Abstractions.Security.Key;
|
||||
|
||||
namespace DigitalData.Core.Abstractions.Security.Services;
|
||||
|
||||
public interface IAsymmetricKeyPool : IAsymmetricKeyFactory
|
||||
{
|
||||
IEnumerable<IAsymmetricDecryptor> Decryptors { get; }
|
||||
|
||||
IAsymmetricDecryptor VaultDecryptor { get; }
|
||||
|
||||
IEnumerable<IAsymmetricTokenDescriptor> TokenDescriptors { get; }
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using DigitalData.Core.Abstractions.Security.Key;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace DigitalData.Core.Abstractions.Security
|
||||
namespace DigitalData.Core.Abstractions.Security.Services
|
||||
{
|
||||
public interface IJwtSignatureHandler<TPrincipal>
|
||||
{
|
||||
@@ -17,9 +17,9 @@
|
||||
<RepositoryUrl>http://git.dd:3000/AppStd/WebCoreModules.git</RepositoryUrl>
|
||||
<PackAsTool>False</PackAsTool>
|
||||
<PackageIcon>core_icon.png</PackageIcon>
|
||||
<Version>3.3.0</Version>
|
||||
<AssemblyVersion>3.3.0</AssemblyVersion>
|
||||
<FileVersion>3.3.0</FileVersion>
|
||||
<Version>3.4.0</Version>
|
||||
<AssemblyVersion>3.4.0</AssemblyVersion>
|
||||
<FileVersion>3.4.0</FileVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
namespace DigitalData.Core.Abstractions.Security
|
||||
{
|
||||
public interface IAsymmetricDecryptor : IAsymmetricPrivateKey
|
||||
{
|
||||
byte[] Decrypt(byte[] data);
|
||||
|
||||
IAsymmetricEncryptor Encryptor { get; }
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
namespace DigitalData.Core.Abstractions.Security
|
||||
{
|
||||
public interface IAsymmetricEncryptor : IAsymmetricPublicKey
|
||||
{
|
||||
byte[] Encrypt(byte[] data);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
namespace DigitalData.Core.Abstractions.Security
|
||||
{
|
||||
public interface IAsymmetricKey
|
||||
{
|
||||
string? Id { get; }
|
||||
|
||||
string Content { get; }
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DigitalData.Core.Abstractions.Security
|
||||
{
|
||||
public interface IAsymmetricKeyFactory
|
||||
{
|
||||
string CreatePrivateKeyPem(int? keySizeInBits = null, bool encrypt = false);
|
||||
|
||||
string CreateEncryptedPrivateKeyPem(
|
||||
PbeEncryptionAlgorithm? pbeEncryptionAlgorithm = null,
|
||||
HashAlgorithmName? hashAlgorithmName = null,
|
||||
int? iterationCount = null,
|
||||
int? keySizeInBits = null,
|
||||
string? password = null);
|
||||
|
||||
string CreateEncryptedPrivateKeyPem(
|
||||
PbeParameters pbeParameters,
|
||||
int? keySizeInBits = null,
|
||||
string? password = null);
|
||||
|
||||
IAsymmetricDecryptor CreateDecryptor(string pem, string? issuer = null, string? audience = null, bool encrypt = false, RSAEncryptionPadding? padding = null);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
namespace DigitalData.Core.Abstractions.Security
|
||||
{
|
||||
public interface IAsymmetricPrivateKey : IAsymmetricKey
|
||||
{
|
||||
bool IsEncrypted { get; }
|
||||
|
||||
IAsymmetricPublicKey PublicKey { get; }
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
namespace DigitalData.Core.Abstractions.Security
|
||||
{
|
||||
public interface IAsymmetricPublicKey : IAsymmetricKey
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace DigitalData.Core.Abstractions.Security
|
||||
{
|
||||
/// <summary>
|
||||
/// Contains some information which used to create a security token. Designed to abstract <see cref="SecurityTokenDescriptor"/>
|
||||
/// </summary>
|
||||
public interface IAsymmetricTokenDescriptor : IAsymmetricPrivateKey, IUniqueSecurityContext
|
||||
{
|
||||
IAsymmetricTokenValidator Validator { get; }
|
||||
|
||||
TimeSpan Lifetime { get; init; }
|
||||
|
||||
#region SecurityTokenDescriptor Map
|
||||
/// <summary>
|
||||
/// Defines the compression algorithm that will be used to compress the JWT token payload.
|
||||
/// </summary>
|
||||
string CompressionAlgorithm { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="EncryptingCredentials"/> used to create a encrypted security token.
|
||||
/// </summary>
|
||||
EncryptingCredentials EncryptingCredentials { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the value of the 'expiration' claim. This value should be in UTC.
|
||||
/// </summary>
|
||||
DateTime? Expires { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time the security token was issued. This value should be in UTC.
|
||||
/// </summary>
|
||||
DateTime? IssuedAt { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the notbefore time for the security token. This value should be in UTC.
|
||||
/// </summary>
|
||||
DateTime? NotBefore { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the token type.
|
||||
/// <remarks> If provided, this will be added as the value for the 'typ' header parameter. In the case of a JWE, this will be added to both the inner (JWS) and the outer token (JWE) header. By default, the value used is 'JWT'.
|
||||
/// If <see cref="AdditionalHeaderClaims"/> also contains 'typ' header claim value, it will override the TokenType provided here.
|
||||
/// This value is used only for JWT tokens and not for SAML/SAML2 tokens</remarks>
|
||||
/// </summary>
|
||||
string TokenType { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="Dictionary{TKey, TValue}"/> which contains any custom header claims that need to be added to the JWT token header.
|
||||
/// The 'alg', 'kid', 'x5t', 'enc', and 'zip' claims are added by default based on the <see cref="SigningCredentials"/>,
|
||||
/// <see cref="EncryptingCredentials"/>, and/or <see cref="CompressionAlgorithm"/> provided and SHOULD NOT be included in this dictionary as this
|
||||
/// will result in an exception being thrown.
|
||||
/// <remarks> These claims are only added to the outer header (in case of a JWE).</remarks>
|
||||
/// </summary>
|
||||
IDictionary<string, object> AdditionalHeaderClaims { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="Dictionary{TKey, TValue}"/> which contains any custom header claims that need to be added to the inner JWT token header.
|
||||
/// The 'alg', 'kid', 'x5t', 'enc', and 'zip' claims are added by default based on the <see cref="SigningCredentials"/>,
|
||||
/// <see cref="EncryptingCredentials"/>, and/or <see cref="CompressionAlgorithm"/> provided and SHOULD NOT be included in this dictionary as this
|
||||
/// will result in an exception being thrown.
|
||||
/// <remarks>
|
||||
/// For JsonWebTokenHandler, these claims are merged with <see cref="AdditionalHeaderClaims"/> while adding to the inner JWT header.
|
||||
/// </remarks>
|
||||
/// </summary>
|
||||
IDictionary<string, object> AdditionalInnerHeaderClaims { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="SigningCredentials"/> used to create a security token.
|
||||
/// </summary>
|
||||
SigningCredentials SigningCredentials { get; }
|
||||
#endregion SecurityTokenDescriptor
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace DigitalData.Core.Abstractions.Security
|
||||
{
|
||||
public interface IAsymmetricTokenValidator : IAsymmetricPublicKey
|
||||
{
|
||||
SecurityKey SecurityKey { get; }
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
namespace DigitalData.Core.Abstractions.Security
|
||||
{
|
||||
public interface ICryptoFactory : IAsymmetricKeyFactory
|
||||
{
|
||||
IEnumerable<IAsymmetricDecryptor> Decryptors { get; }
|
||||
|
||||
IAsymmetricDecryptor VaultDecryptor { get; }
|
||||
|
||||
IEnumerable<IAsymmetricTokenDescriptor> TokenDescriptors { get; }
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
namespace DigitalData.Core.Abstractions.Security
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a unique security context that identifies an issuer and an audience.
|
||||
/// </summary>
|
||||
public interface IUniqueSecurityContext
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the issuer identifier for this security context.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The issuer typically represents the entity that issues a token or a cryptographic key.
|
||||
/// </remarks>
|
||||
string Issuer { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the audience identifier for this security context.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The audience typically represents the intended recipient or target of a token or cryptographic operation.
|
||||
/// </remarks>
|
||||
string Audience { get; }
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Text;
|
||||
|
||||
namespace DigitalData.Core.Abstractions.Security
|
||||
{
|
||||
public static class SecurityExtensions
|
||||
{
|
||||
#region Unique Security Context
|
||||
public static IEnumerable<TUniqueSecurityContext> GetByIssuer<TUniqueSecurityContext>(this IEnumerable<TUniqueSecurityContext> contextes, string issuer) where TUniqueSecurityContext: IUniqueSecurityContext
|
||||
=> contextes.Where(c => c.Issuer == issuer);
|
||||
|
||||
public static IEnumerable<TUniqueSecurityContext> GetByAudience<TUniqueSecurityContext>(this IEnumerable<TUniqueSecurityContext> contextes, string audience) where TUniqueSecurityContext : IUniqueSecurityContext
|
||||
=> contextes.Where(c => c.Audience == audience);
|
||||
|
||||
public static TUniqueSecurityContext Get<TUniqueSecurityContext>(this IEnumerable<TUniqueSecurityContext> contextes, string issuer, string audience) where TUniqueSecurityContext : IUniqueSecurityContext
|
||||
=> contextes.Where(c => c.Issuer == issuer && c.Audience == audience).SingleOrDefault()
|
||||
?? throw new InvalidOperationException($"Exactly one {typeof(TUniqueSecurityContext).Name} must exist with Issuer: '{issuer}' and Audience: '{audience}'.");
|
||||
|
||||
public static bool TryGet<TUniqueSecurityContext>(this IEnumerable<TUniqueSecurityContext> contextes, string issuer, string audience, out TUniqueSecurityContext context) where TUniqueSecurityContext : IUniqueSecurityContext
|
||||
{
|
||||
#pragma warning disable CS8601 // Possible null reference assignment.
|
||||
context = contextes.SingleOrDefault(c => c.Issuer == issuer && c.Audience == audience);
|
||||
#pragma warning restore CS8601 // Possible null reference assignment.
|
||||
return context is not null;
|
||||
}
|
||||
|
||||
public static TUniqueSecurityContext Match<TUniqueSecurityContext>(this IEnumerable<TUniqueSecurityContext> contextes, IUniqueSecurityContext lookupContext) where TUniqueSecurityContext : IUniqueSecurityContext
|
||||
=> contextes.Get(lookupContext.Issuer, lookupContext.Audience);
|
||||
|
||||
public static bool TryMatch<TUniqueSecurityContext>(this IEnumerable<TUniqueSecurityContext> contextes, IUniqueSecurityContext lookupContext, out TUniqueSecurityContext context) where TUniqueSecurityContext : IUniqueSecurityContext
|
||||
=> contextes.TryGet(lookupContext.Issuer, lookupContext.Audience, out context);
|
||||
#endregion Unique Security Context
|
||||
|
||||
#region De/serilization
|
||||
internal static byte[] Base64ToByte(this string base64String) => Convert.FromBase64String(base64String);
|
||||
|
||||
internal static string BytesToString(this byte[] bytes) => Encoding.UTF8.GetString(bytes);
|
||||
|
||||
internal static string ToBase64String(this byte[] bytes) => Convert.ToBase64String(bytes);
|
||||
|
||||
internal static byte[] ToBytes(this string str) => System.Text.Encoding.UTF8.GetBytes(str);
|
||||
|
||||
public static string Decrypt(this IAsymmetricDecryptor decryptor, string data) => decryptor
|
||||
.Decrypt(data.Base64ToByte()).BytesToString();
|
||||
#endregion De/serilization
|
||||
|
||||
#region Asymmetric Encryptor
|
||||
public static string Encrypt(this IAsymmetricEncryptor encryptor, string data) => encryptor.Encrypt(data.ToBytes()).ToBase64String();
|
||||
#endregion Asymmetric Encryptor
|
||||
|
||||
#region Jwt Signature Handler
|
||||
public static string WriteToken<TPrincipal>(this IJwtSignatureHandler<TPrincipal> handler, SecurityTokenDescriptor descriptor)
|
||||
=> handler.WriteToken(handler.CreateToken(descriptor));
|
||||
|
||||
public static string WriteToken<TPrincipal>(this IJwtSignatureHandler<TPrincipal> handler, TPrincipal subject, IAsymmetricTokenDescriptor descriptor)
|
||||
=> handler.WriteToken(handler.CreateToken(subject: subject, descriptor: descriptor));
|
||||
|
||||
public static string WriteToken<TPrincipal>(this IJwtSignatureHandler<TPrincipal> handler, TPrincipal subject, string issuer, string audience)
|
||||
=> handler.WriteToken(handler.CreateToken(subject: subject, issuer: issuer, audience: audience));
|
||||
#endregion Jwt Signature Handler
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,10 @@
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace DigitalData.Core.Security.Config
|
||||
{
|
||||
public class ClaimDescriptor<TPrincipal>
|
||||
{
|
||||
public Func<TPrincipal, IDictionary<string, object>>? CreateClaims { get; init; }
|
||||
namespace DigitalData.Core.Security.Config;
|
||||
|
||||
public Func<TPrincipal, ClaimsIdentity>? CreateSubject { get; init; }
|
||||
}
|
||||
public class ClaimDescriptor<TPrincipal>
|
||||
{
|
||||
public Func<TPrincipal, IDictionary<string, object>>? CreateClaims { get; init; }
|
||||
|
||||
public Func<TPrincipal, ClaimsIdentity>? CreateSubject { get; init; }
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
using DigitalData.Core.Security.RSAKey;
|
||||
|
||||
namespace DigitalData.Core.Security.Config
|
||||
{
|
||||
public class CryptoFactoryParams : RSAFactoryParams
|
||||
{
|
||||
public string PemDirectory { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Represents the separator used to concatenate the components of a file-related token string.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The resulting file-related token string is constructed as follows:
|
||||
/// <c>string.Join(FileNameSeparator, Issuer, Audience, Secret_version)</c>.
|
||||
/// If <c>Secret_version</c> is not null, it will be included in the concatenation.
|
||||
/// </remarks>
|
||||
/// <example>
|
||||
/// For example, if <c>FileNameSeparator = "_-_"</c>, the output might look like:
|
||||
/// <c>"Issuer_-_Audience_-_Secret_version"</c>.
|
||||
/// </example>
|
||||
public string FileNameSeparator { get; init; } = "_-_";
|
||||
|
||||
public string FileExtension { get; init; } = "pem";
|
||||
|
||||
/// <summary>
|
||||
///This is the subtext of the pem file name. For the file to be automatically renewed, the name must be assigned to change periodically. For example, by default MM/2 will be refreshed every 2 months.
|
||||
/// <br />
|
||||
/// - <see cref="StringExtensions.ToTag(DateTime, string)" /> is used when converting to tag.
|
||||
/// <br />
|
||||
/// - If the format contains the symbol “//”, the method divides the numeric value obtained from the left side of the format
|
||||
/// by one minus the numeric value obtained from the right side of the format string and adds one. For instance:
|
||||
/// <br />
|
||||
/// - If the date is 02.03.2024 and the format is "MM//2", it extracts the month (02), subtracts one (3), divides it by 2,
|
||||
/// rounds down the outgoing number (1), adds one to the number (resulting in 2).
|
||||
/// <br />
|
||||
/// - If the format does not contain "//", the method uses the default <see cref="DateTime.ToString"/> format.
|
||||
/// <br />
|
||||
/// This method provides a way to format the date based on typical or customized rules, including mathematical operations like division.
|
||||
/// </summary>
|
||||
public string DateTagFormat { get; init; } = "MM//2";
|
||||
|
||||
public IEnumerable<RSADecryptor> Decryptors { get; init; } = new List<RSADecryptor>();
|
||||
|
||||
public IEnumerable<RSATokenDescriptor> TokenDescriptors { get; init; } = new List<RSATokenDescriptor>();
|
||||
|
||||
public RSADecryptor? VaultDecryptor { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,13 @@
|
||||
using AutoMapper;
|
||||
using DigitalData.Core.Abstractions.Security;
|
||||
using DigitalData.Core.Abstractions.Security.Key;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace DigitalData.Core.Security.Config
|
||||
namespace DigitalData.Core.Security.Config;
|
||||
|
||||
public class MappingProfile : Profile
|
||||
{
|
||||
public class MappingProfile : Profile
|
||||
public MappingProfile()
|
||||
{
|
||||
public MappingProfile()
|
||||
{
|
||||
CreateMap<IAsymmetricTokenDescriptor, SecurityTokenDescriptor>();
|
||||
}
|
||||
CreateMap<IAsymmetricTokenDescriptor, SecurityTokenDescriptor>();
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
using System.Reflection;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace DigitalData.Core.Security.Config
|
||||
{
|
||||
public class RSAFactoryParams
|
||||
{
|
||||
public int KeySizeInBits { get; init; } = 2048;
|
||||
|
||||
public string PbePassword { internal get; init; } = Secrets.PBE_PASSWORD;
|
||||
|
||||
public PbeEncryptionAlgorithm PbeEncryptionAlgorithm { get; init; } = PbeEncryptionAlgorithm.Aes256Cbc;
|
||||
|
||||
public HashAlgorithmName PbeHashAlgorithm { get; init; } = HashAlgorithmName.SHA256;
|
||||
|
||||
// TODO: add as json converter to IConfigurIConfiguration.Config
|
||||
public string PbeHashAlgorithmName
|
||||
{
|
||||
get => PbeHashAlgorithm.ToString();
|
||||
init => PbeHashAlgorithm = (typeof(HashAlgorithmName).GetProperty(value, BindingFlags.Public | BindingFlags.Static)?.GetValue(null) is HashAlgorithmName hashAlgorithmName)
|
||||
? hashAlgorithmName
|
||||
: new(value);
|
||||
}
|
||||
|
||||
public int PbeIterationCount { get; init; } = 100_000;
|
||||
|
||||
public string EncryptedPrivateKeyPemLabel { get; init; } = "ENCRYPTED PRIVATE KEY";
|
||||
|
||||
private readonly Lazy<PbeParameters> _lazyPbeParameters;
|
||||
|
||||
[JsonIgnore]
|
||||
public PbeParameters PbeParameters => _lazyPbeParameters.Value;
|
||||
|
||||
public RSAFactoryParams()
|
||||
{
|
||||
_lazyPbeParameters = new(() => new PbeParameters(PbeEncryptionAlgorithm, PbeHashAlgorithm, PbeIterationCount));
|
||||
}
|
||||
}
|
||||
}
|
||||
94
DigitalData.Core.Security/Config/RSAParams.cs
Normal file
94
DigitalData.Core.Security/Config/RSAParams.cs
Normal file
@@ -0,0 +1,94 @@
|
||||
using DigitalData.Core.Security.RSAKey.Auth;
|
||||
using DigitalData.Core.Security.RSAKey.Crypto;
|
||||
using System.Reflection;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DigitalData.Core.Security.Config;
|
||||
|
||||
public class RSAParams
|
||||
{
|
||||
#region Factory Params
|
||||
public int KeySizeInBits { get; init; } = Default.KeySizeInBits;
|
||||
|
||||
public string PbePassword { internal get; init; } = Default.PbePassword;
|
||||
|
||||
public PbeEncryptionAlgorithm PbeEncryptionAlgorithm { get; init; } = Default.PbeEncryptionAlgorithm;
|
||||
|
||||
public HashAlgorithmName PbeHashAlgorithm { get; init; } = Default.PbeHashAlgorithm;
|
||||
|
||||
// TODO: add as json converter to IConfigurIConfiguration.Config
|
||||
public string PbeHashAlgorithmName
|
||||
{
|
||||
get => PbeHashAlgorithm.ToString();
|
||||
init => PbeHashAlgorithm = (typeof(HashAlgorithmName).GetProperty(value, BindingFlags.Public | BindingFlags.Static)?.GetValue(null) is HashAlgorithmName hashAlgorithmName)
|
||||
? hashAlgorithmName
|
||||
: new(value);
|
||||
}
|
||||
|
||||
public int PbeIterationCount { get; init; } = Default.PbeIterationCount;
|
||||
|
||||
public string EncryptedPrivateKeyPemLabel { get; init; } = Default.EncryptedPrivateKeyPemLabel;
|
||||
|
||||
public PbeParameters PbeParameters => new(PbeEncryptionAlgorithm, PbeHashAlgorithm, PbeIterationCount);
|
||||
|
||||
public static class Default
|
||||
{
|
||||
public static readonly int KeySizeInBits = 2048;
|
||||
|
||||
public static readonly string PbePassword = Secrets.PBE_PASSWORD;
|
||||
|
||||
public static readonly PbeEncryptionAlgorithm PbeEncryptionAlgorithm = PbeEncryptionAlgorithm.Aes256Cbc;
|
||||
|
||||
public static readonly HashAlgorithmName PbeHashAlgorithm = HashAlgorithmName.SHA256;
|
||||
|
||||
public static readonly int PbeIterationCount = 100_000;
|
||||
|
||||
public static readonly string EncryptedPrivateKeyPemLabel = "ENCRYPTED PRIVATE KEY";
|
||||
|
||||
public static readonly PbeParameters PbeParameters = new(PbeEncryptionAlgorithm, PbeHashAlgorithm, PbeIterationCount);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Pool Params
|
||||
public string PemDirectory { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Represents the separator used to concatenate the components of a file-related token string.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The resulting file-related token string is constructed as follows:
|
||||
/// <c>string.Join(FileNameSeparator, Issuer, Audience, Secret_version)</c>.
|
||||
/// If <c>Secret_version</c> is not null, it will be included in the concatenation.
|
||||
/// </remarks>
|
||||
/// <example>
|
||||
/// For example, if <c>FileNameSeparator = "_-_"</c>, the output might look like:
|
||||
/// <c>"Issuer_-_Audience_-_Secret_version"</c>.
|
||||
/// </example>
|
||||
public string FileNameSeparator { get; init; } = "_-_";
|
||||
|
||||
public string FileExtension { get; init; } = "pem";
|
||||
|
||||
/// <summary>
|
||||
///This is the subtext of the pem file name. For the file to be automatically renewed, the name must be assigned to change periodically. For example, by default MM/2 will be refreshed every 2 months.
|
||||
/// <br />
|
||||
/// - <see cref="StringExtensions.ToTag(DateTime, string)" /> is used when converting to tag.
|
||||
/// <br />
|
||||
/// - If the format contains the symbol “//”, the method divides the numeric value obtained from the left side of the format
|
||||
/// by one minus the numeric value obtained from the right side of the format string and adds one. For instance:
|
||||
/// <br />
|
||||
/// - If the date is 02.03.2024 and the format is "MM//2", it extracts the month (02), subtracts one (3), divides it by 2,
|
||||
/// rounds down the outgoing number (1), adds one to the number (resulting in 2).
|
||||
/// <br />
|
||||
/// - If the format does not contain "//", the method uses the default <see cref="DateTime.ToString"/> format.
|
||||
/// <br />
|
||||
/// This method provides a way to format the date based on typical or customized rules, including mathematical operations like division.
|
||||
/// </summary>
|
||||
public string DateTagFormat { get; init; } = "MM//2";
|
||||
|
||||
public IEnumerable<RSADecryptor> Decryptors { get; init; } = new List<RSADecryptor>();
|
||||
|
||||
public IEnumerable<RSATokenDescriptor> TokenDescriptors { get; init; } = new List<RSATokenDescriptor>();
|
||||
|
||||
public RSADecryptor? VaultDecryptor { get; init; }
|
||||
#endregion
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
using DigitalData.Core.Abstractions.Security;
|
||||
using DigitalData.Core.Security.Config;
|
||||
using DigitalData.Core.Security.RSAKey;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace DigitalData.Core.Security
|
||||
{
|
||||
public class CryptoFactory : RSAFactory<CryptoFactoryParams>, ICryptoFactory, IAsymmetricKeyFactory
|
||||
{
|
||||
public IEnumerable<IAsymmetricDecryptor> Decryptors { get; }
|
||||
|
||||
/// <summary>
|
||||
/// It is a separate decryptor for permanently stored encrypted data. It is assigned to the first Default decryptor by default.
|
||||
/// </summary>
|
||||
public IAsymmetricDecryptor VaultDecryptor { get; }
|
||||
|
||||
public IEnumerable<IAsymmetricTokenDescriptor> TokenDescriptors { get; init; } = new List<IAsymmetricTokenDescriptor>();
|
||||
|
||||
public CryptoFactory(IOptions<CryptoFactoryParams> options, ILogger<CryptoFactory>? logger = null) : base(options)
|
||||
{
|
||||
logger?.LogInformation("Core.Secrets version: {Version}, Created on: {CreationDate}.", Secrets.Version, Secrets.CreationDate.ToString("dd.MM.yyyy"));
|
||||
|
||||
if (!_params.Decryptors.Any())
|
||||
throw new InvalidOperationException(
|
||||
"Any decryptor is not found. Ensure that at least one decryptor is configured in the provided parameters. " +
|
||||
"This issue typically arises if the configuration for decryptors is incomplete or missing. " +
|
||||
"Check the 'Decryptors' collection in the configuration and verify that it contains valid entries."
|
||||
);
|
||||
|
||||
Decryptors = _params.Decryptors;
|
||||
|
||||
TokenDescriptors = _params.TokenDescriptors;
|
||||
|
||||
VaultDecryptor = _params.VaultDecryptor ?? Decryptors.First();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
using DigitalData.Core.Abstractions.Security;
|
||||
using DigitalData.Core.Security.Config;
|
||||
using DigitalData.Core.Security.RSAKey;
|
||||
using DigitalData.Core.Security.Services;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace DigitalData.Core.Security
|
||||
{
|
||||
public static class DIExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers a custom asym crypt service with specified parameters from the given configuration section.
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
/// <param name="section"></param>
|
||||
/// <returns>The updated <see cref="IServiceCollection"/> with the RSA Factory registered.</returns>
|
||||
public static IServiceCollection AddCryptoFactory(this IServiceCollection services, IConfiguration configuration) => services
|
||||
.Configure<CryptoFactoryParams>(configuration)
|
||||
.AddAutoMapper(typeof(MappingProfile).Assembly)
|
||||
.AddSingleton<ICryptoFactory, CryptoFactory>()
|
||||
.AddHostedService<PemFileInitalizer>();
|
||||
|
||||
public static IServiceCollection AddJwtSignatureHandler<TPrincipal>(this IServiceCollection services,
|
||||
Func<TPrincipal, IDictionary<string, object>>? claimsMapper = null,
|
||||
Func<TPrincipal, ClaimsIdentity>? subjectMapper = null)
|
||||
=> services
|
||||
.AddSingleton<IJwtSignatureHandler<TPrincipal>, JwtSignatureHandler<TPrincipal>>()
|
||||
.AddSingleton(sp => Options.Create(new ClaimDescriptor<TPrincipal>
|
||||
{
|
||||
CreateClaims = claimsMapper,
|
||||
CreateSubject = subjectMapper
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<PackageId>DigitalData.Core.Security</PackageId>
|
||||
<Version>1.0.0</Version>
|
||||
<Version>1.1.0</Version>
|
||||
<Company>Digital Data GmbH</Company>
|
||||
<Product>Digital Data GmbH</Product>
|
||||
<Description>This package provides RSA-based security functionalities as an implementation of the DigitalData.Core.Abstractions.Security library. It supports robust encryption and decryption operations, as well as JWT signing and validation for secure authentication and data integrity.</Description>
|
||||
@@ -15,8 +15,8 @@
|
||||
<PackageIcon>core_icon.png</PackageIcon>
|
||||
<RepositoryUrl>http://git.dd:3000/AppStd/WebCoreModules.git</RepositoryUrl>
|
||||
<PackageTags>digital data core security</PackageTags>
|
||||
<AssemblyVersion>1.0.0</AssemblyVersion>
|
||||
<FileVersion>1.0.0</FileVersion>
|
||||
<AssemblyVersion>1.1.0</AssemblyVersion>
|
||||
<FileVersion>1.1.0</FileVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -33,7 +33,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\DigitalData.Core.Abstractions\DigitalData.Core.Abstractions.csproj" />
|
||||
<ProjectReference Include="..\DigitalData.Core.Abstractions.Security\DigitalData.Core.Abstractions.Security.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
using AutoMapper;
|
||||
using DigitalData.Core.Abstractions.Security;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace DigitalData.Core.Security
|
||||
{
|
||||
internal static class Extension
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts a <see cref="DateTime"/> to a formatted string based on the specified format string.
|
||||
/// <br />
|
||||
/// - If the format contains the symbol “//”, the method divides the numeric value obtained from the left side of the format
|
||||
/// by one minus the numeric value obtained from the right side of the format string and adds one. For instance:
|
||||
/// <br />
|
||||
/// - If the date is 02.03.2024 and the format is "MM//2", it extracts the month (02), subtracts one (3), divides it by 2,
|
||||
/// rounds down the outgoing number (1), adds one to the number (resulting in 2).
|
||||
/// <br />
|
||||
/// - If the format does not contain "//", the method uses the default <see cref="DateTime.ToString"/> format.
|
||||
/// <br />
|
||||
/// </summary>
|
||||
/// <param name="date">The <see cref="DateTime"/> value to be formatted.</param>
|
||||
/// <param name="format">The format string that dictates the formatting of the date. If the format includes the "//" symbol,
|
||||
/// it splits the string at "//" and divides the left-side value by the right-side value. The format string can include standard
|
||||
/// <see cref="DateTime.ToString"/> format patterns.</param>
|
||||
/// <returns>A string representation of the formatted date, or the result of the division operation if "//" is present in the format.</returns>
|
||||
/// <exception cref="ArgumentException">Thrown if the format string is invalid, such as having an incorrect number of parts after "//".</exception>
|
||||
/// <exception cref="DivideByZeroException">Thrown if the right side of the "//" contains a zero, resulting in division by zero.</exception>
|
||||
/// <exception cref="FormatException">Thrown if either the left-side or right-side value of "//" cannot be parsed as an integer.</exception>
|
||||
internal static string ToTag(this DateTime date, string format)
|
||||
{
|
||||
if (format is not null && format.Contains("//"))
|
||||
{
|
||||
var subStrings = format.Split("//");
|
||||
|
||||
if (subStrings.Length != 2)
|
||||
throw new ArgumentException($"Date tag format {format} is invalid. It must contain exactly one '//' separator.", nameof(format));
|
||||
|
||||
var formattedLeft = date.ToString(subStrings[0]);
|
||||
|
||||
if (!int.TryParse(formattedLeft, out var dateValue))
|
||||
throw new FormatException($"The left-side value ({formattedLeft}) of the format could not be parsed to an integer.");
|
||||
|
||||
if (!int.TryParse(subStrings[1], out var divisor))
|
||||
throw new FormatException($"The right-side value ({divisor}) of the format could not be parsed to an integer.");
|
||||
|
||||
if (divisor == 0)
|
||||
throw new DivideByZeroException($"Date tag format {format} includes division by zero, which is not allowed.");
|
||||
|
||||
var result = (dateValue - 1) / divisor + 1;
|
||||
return result.ToString();
|
||||
}
|
||||
|
||||
return date.ToString(format);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts a <see cref="DateTime"/> to a formatted string based on the specified format string.
|
||||
/// <br />
|
||||
/// - If the format contains the symbol “//”, the method divides the numeric value obtained from the left side of the format
|
||||
/// by one minus the numeric value obtained from the right side of the format string and adds one. For instance:
|
||||
/// <br />
|
||||
/// - If the date is 02.03.2024 and the format is "MM//2", it extracts the month (02), subtracts one (3), divides it by 2,
|
||||
/// rounds down the outgoing number (1), adds one to the number (resulting in 2).
|
||||
/// <br />
|
||||
/// - If the format does not contain "//", the method uses the default <see cref="DateTime.ToString"/> format.
|
||||
/// <br />
|
||||
/// This method provides a way to format the date based on typical or customized rules, including mathematical operations like division.
|
||||
/// </summary>
|
||||
/// <param name="date">The <see cref="DateOnly"/> value to be formatted. It will convert to DateTime to use the method shared with DateTime.</param>
|
||||
/// <param name="format">The format string that dictates the formatting of the date. If the format includes the "//" symbol,
|
||||
/// it splits the string at "//" and divides the left-side value by the right-side value. The format string can include standard
|
||||
/// <see cref="DateTime.ToString"/> format patterns.</param>
|
||||
/// <returns>A string representation of the formatted date, or the result of the division operation if "//" is present in the format.</returns>
|
||||
/// <exception cref="ArgumentException">Thrown if the format string is invalid, such as having an incorrect number of parts after "//".</exception>
|
||||
/// <exception cref="DivideByZeroException">Thrown if the right side of the "//" contains a zero, resulting in division by zero.</exception>
|
||||
/// <exception cref="FormatException">Thrown if either the left-side or right-side value of "//" cannot be parsed as an integer.</exception>
|
||||
internal static string ToTag(this DateOnly date, string format) => date.ToDateTime(new()).ToTag(format);
|
||||
|
||||
/// <summary>
|
||||
/// Maps a <see cref="RSATokenDescriptor"/> to a <see cref="SecurityTokenDescriptor"/>.
|
||||
/// </summary>
|
||||
/// <param name="mapper">The <see cref="IMapper"/> instance used for mapping.</param>
|
||||
/// <param name="description">The <see cref="RSATokenDescriptor"/> instance to be mapped.</param>
|
||||
/// <returns>A <see cref="SecurityTokenDescriptor"/> instance populated with the mapped values.</returns>
|
||||
/// <exception cref="ArgumentNullException">Thrown if <paramref name="mapper"/> or <paramref name="description"/> is <c>null</c>.</exception>
|
||||
internal static SecurityTokenDescriptor Map(this IMapper mapper, IAsymmetricTokenDescriptor description)
|
||||
=> mapper.Map(description, new SecurityTokenDescriptor());
|
||||
}
|
||||
}
|
||||
36
DigitalData.Core.Security/Extensions/DIExtensions.cs
Normal file
36
DigitalData.Core.Security/Extensions/DIExtensions.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
using DigitalData.Core.Abstractions.Security.Services;
|
||||
using DigitalData.Core.Security.Config;
|
||||
using DigitalData.Core.Security.Services;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace DigitalData.Core.Security.Extensions;
|
||||
|
||||
public static class DIExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers a custom asym crypt service with specified parameters from the given configuration section.
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
/// <param name="section"></param>
|
||||
/// <returns>The updated <see cref="IServiceCollection"/> with the RSA Factory registered.</returns>
|
||||
public static IServiceCollection AddCryptoFactory(this IServiceCollection services, IConfiguration configuration) => services
|
||||
.Configure<RSAParams>(configuration)
|
||||
.AddAutoMapper(typeof(MappingProfile).Assembly)
|
||||
.AddSingleton<IAsymmetricKeyPool, RSAPool>()
|
||||
.AddSingleton<IAsymmetricKeyFactory, RSAFactory>()
|
||||
.AddHostedService<PemFileInitalizer>();
|
||||
|
||||
public static IServiceCollection AddJwtSignatureHandler<TPrincipal>(this IServiceCollection services,
|
||||
Func<TPrincipal, IDictionary<string, object>>? claimsMapper = null,
|
||||
Func<TPrincipal, ClaimsIdentity>? subjectMapper = null)
|
||||
=> services
|
||||
.AddSingleton<IJwtSignatureHandler<TPrincipal>, JwtSignatureHandler<TPrincipal>>()
|
||||
.AddSingleton(sp => Options.Create(new ClaimDescriptor<TPrincipal>
|
||||
{
|
||||
CreateClaims = claimsMapper,
|
||||
CreateSubject = subjectMapper
|
||||
}));
|
||||
}
|
||||
88
DigitalData.Core.Security/Extensions/Extension.cs
Normal file
88
DigitalData.Core.Security/Extensions/Extension.cs
Normal file
@@ -0,0 +1,88 @@
|
||||
using AutoMapper;
|
||||
using DigitalData.Core.Abstractions.Security.Key;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace DigitalData.Core.Security.Extensions;
|
||||
|
||||
internal static class Extension
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts a <see cref="DateTime"/> to a formatted string based on the specified format string.
|
||||
/// <br />
|
||||
/// - If the format contains the symbol “//”, the method divides the numeric value obtained from the left side of the format
|
||||
/// by one minus the numeric value obtained from the right side of the format string and adds one. For instance:
|
||||
/// <br />
|
||||
/// - If the date is 02.03.2024 and the format is "MM//2", it extracts the month (02), subtracts one (3), divides it by 2,
|
||||
/// rounds down the outgoing number (1), adds one to the number (resulting in 2).
|
||||
/// <br />
|
||||
/// - If the format does not contain "//", the method uses the default <see cref="DateTime.ToString"/> format.
|
||||
/// <br />
|
||||
/// </summary>
|
||||
/// <param name="date">The <see cref="DateTime"/> value to be formatted.</param>
|
||||
/// <param name="format">The format string that dictates the formatting of the date. If the format includes the "//" symbol,
|
||||
/// it splits the string at "//" and divides the left-side value by the right-side value. The format string can include standard
|
||||
/// <see cref="DateTime.ToString"/> format patterns.</param>
|
||||
/// <returns>A string representation of the formatted date, or the result of the division operation if "//" is present in the format.</returns>
|
||||
/// <exception cref="ArgumentException">Thrown if the format string is invalid, such as having an incorrect number of parts after "//".</exception>
|
||||
/// <exception cref="DivideByZeroException">Thrown if the right side of the "//" contains a zero, resulting in division by zero.</exception>
|
||||
/// <exception cref="FormatException">Thrown if either the left-side or right-side value of "//" cannot be parsed as an integer.</exception>
|
||||
internal static string ToTag(this DateTime date, string format)
|
||||
{
|
||||
if (format is not null && format.Contains("//"))
|
||||
{
|
||||
var subStrings = format.Split("//");
|
||||
|
||||
if (subStrings.Length != 2)
|
||||
throw new ArgumentException($"Date tag format {format} is invalid. It must contain exactly one '//' separator.", nameof(format));
|
||||
|
||||
var formattedLeft = date.ToString(subStrings[0]);
|
||||
|
||||
if (!int.TryParse(formattedLeft, out var dateValue))
|
||||
throw new FormatException($"The left-side value ({formattedLeft}) of the format could not be parsed to an integer.");
|
||||
|
||||
if (!int.TryParse(subStrings[1], out var divisor))
|
||||
throw new FormatException($"The right-side value ({divisor}) of the format could not be parsed to an integer.");
|
||||
|
||||
if (divisor == 0)
|
||||
throw new DivideByZeroException($"Date tag format {format} includes division by zero, which is not allowed.");
|
||||
|
||||
var result = (dateValue - 1) / divisor + 1;
|
||||
return result.ToString();
|
||||
}
|
||||
|
||||
return date.ToString(format);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts a <see cref="DateTime"/> to a formatted string based on the specified format string.
|
||||
/// <br />
|
||||
/// - If the format contains the symbol “//”, the method divides the numeric value obtained from the left side of the format
|
||||
/// by one minus the numeric value obtained from the right side of the format string and adds one. For instance:
|
||||
/// <br />
|
||||
/// - If the date is 02.03.2024 and the format is "MM//2", it extracts the month (02), subtracts one (3), divides it by 2,
|
||||
/// rounds down the outgoing number (1), adds one to the number (resulting in 2).
|
||||
/// <br />
|
||||
/// - If the format does not contain "//", the method uses the default <see cref="DateTime.ToString"/> format.
|
||||
/// <br />
|
||||
/// This method provides a way to format the date based on typical or customized rules, including mathematical operations like division.
|
||||
/// </summary>
|
||||
/// <param name="date">The <see cref="DateOnly"/> value to be formatted. It will convert to DateTime to use the method shared with DateTime.</param>
|
||||
/// <param name="format">The format string that dictates the formatting of the date. If the format includes the "//" symbol,
|
||||
/// it splits the string at "//" and divides the left-side value by the right-side value. The format string can include standard
|
||||
/// <see cref="DateTime.ToString"/> format patterns.</param>
|
||||
/// <returns>A string representation of the formatted date, or the result of the division operation if "//" is present in the format.</returns>
|
||||
/// <exception cref="ArgumentException">Thrown if the format string is invalid, such as having an incorrect number of parts after "//".</exception>
|
||||
/// <exception cref="DivideByZeroException">Thrown if the right side of the "//" contains a zero, resulting in division by zero.</exception>
|
||||
/// <exception cref="FormatException">Thrown if either the left-side or right-side value of "//" cannot be parsed as an integer.</exception>
|
||||
internal static string ToTag(this DateOnly date, string format) => date.ToDateTime(new()).ToTag(format);
|
||||
|
||||
/// <summary>
|
||||
/// Maps a <see cref="RSATokenDescriptor"/> to a <see cref="SecurityTokenDescriptor"/>.
|
||||
/// </summary>
|
||||
/// <param name="mapper">The <see cref="IMapper"/> instance used for mapping.</param>
|
||||
/// <param name="description">The <see cref="RSATokenDescriptor"/> instance to be mapped.</param>
|
||||
/// <returns>A <see cref="SecurityTokenDescriptor"/> instance populated with the mapped values.</returns>
|
||||
/// <exception cref="ArgumentNullException">Thrown if <paramref name="mapper"/> or <paramref name="description"/> is <c>null</c>.</exception>
|
||||
internal static SecurityTokenDescriptor Map(this IMapper mapper, IAsymmetricTokenDescriptor description)
|
||||
=> mapper.Map(description, new SecurityTokenDescriptor());
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
using DigitalData.Core.Abstractions.Security;
|
||||
using DigitalData.Core.Security.Config;
|
||||
using DigitalData.Core.Security.RSAKey;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace DigitalData.Core.Security
|
||||
{
|
||||
public static class Instance
|
||||
{
|
||||
private static readonly Lazy<RSAFactory<RSAFactoryParams>> LazyInstance = new(() => new(Options.Create<RSAFactoryParams>(new())));
|
||||
|
||||
public static IAsymmetricKeyFactory RSAFactory => LazyInstance.Value;
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
using AutoMapper;
|
||||
using DigitalData.Core.Abstractions.Security;
|
||||
using DigitalData.Core.Security.Config;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
|
||||
namespace DigitalData.Core.Security
|
||||
{
|
||||
public class JwtSignatureHandler<TPrincipal> : JwtSecurityTokenHandler, IJwtSignatureHandler<TPrincipal>
|
||||
{
|
||||
private readonly ClaimDescriptor<TPrincipal> _claimDescriptor;
|
||||
|
||||
private readonly IMapper _mapper;
|
||||
|
||||
private readonly ICryptoFactory _cryptoFactory;
|
||||
|
||||
public JwtSignatureHandler(IOptions<ClaimDescriptor<TPrincipal>> claimDescriptorOptions, IMapper mapper, ICryptoFactory cryptoFactory)
|
||||
{
|
||||
_claimDescriptor = claimDescriptorOptions.Value;
|
||||
_mapper = mapper;
|
||||
_cryptoFactory = cryptoFactory;
|
||||
}
|
||||
|
||||
public SecurityToken CreateToken(TPrincipal subject, IAsymmetricTokenDescriptor descriptor)
|
||||
{
|
||||
var sDescriptor = _mapper.Map(descriptor);
|
||||
sDescriptor.Claims = _claimDescriptor.CreateClaims?.Invoke(subject);
|
||||
sDescriptor.Subject = _claimDescriptor.CreateSubject?.Invoke(subject);
|
||||
return CreateToken(sDescriptor);
|
||||
}
|
||||
|
||||
public SecurityToken CreateToken(TPrincipal subject, string issuer, string audience)
|
||||
{
|
||||
var descriptor = _cryptoFactory.TokenDescriptors.Get(issuer: issuer, audience: audience)
|
||||
?? throw new InvalidOperationException($"No or multiple token description found for issuer '{issuer}' and audience '{audience}'.");
|
||||
return CreateToken(subject: subject, descriptor: descriptor);
|
||||
}
|
||||
}
|
||||
}
|
||||
119
DigitalData.Core.Security/RSAKey/Auth/RSATokenDescriptor.cs
Normal file
119
DigitalData.Core.Security/RSAKey/Auth/RSATokenDescriptor.cs
Normal file
@@ -0,0 +1,119 @@
|
||||
using DigitalData.Core.Abstractions.Security.Key;
|
||||
using DigitalData.Core.Security.RSAKey.Base;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace DigitalData.Core.Security.RSAKey.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Contains some information which used to create a security token. Designed to abstract <see cref="SecurityTokenDescriptor"/>
|
||||
/// </summary>
|
||||
public class RSATokenDescriptor : RSAPrivateKey, IAsymmetricTokenDescriptor
|
||||
{
|
||||
private readonly Lazy<RSATokenValidator> _lazyTokenValidator;
|
||||
|
||||
public IAsymmetricTokenValidator Validator => _lazyTokenValidator.Value;
|
||||
|
||||
public required TimeSpan Lifetime { get; init; }
|
||||
|
||||
#region SecurityTokenDescriptor Map
|
||||
/// <summary>
|
||||
/// Gets or sets the value of the 'audience' claim.
|
||||
/// </summary>
|
||||
public required string Audience { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Defines the compression algorithm that will be used to compress the JWT token payload.
|
||||
/// </summary>
|
||||
public string CompressionAlgorithm { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="EncryptingCredentials"/> used to create a encrypted security token.
|
||||
/// </summary>
|
||||
public EncryptingCredentials EncryptingCredentials { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the value of the 'expiration' claim. This value should be in UTC.
|
||||
/// The expiration time is the sum of DateTime.Now and LifeTime.
|
||||
/// </summary>
|
||||
public DateTime? Expires => DateTime.Now.AddTicks(Lifetime.Ticks);
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the issuer of this <see cref="SecurityTokenDescriptor"/>.
|
||||
/// </summary>
|
||||
public required string Issuer { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time the security token was issued. This value should be in UTC.
|
||||
/// </summary>
|
||||
public DateTime? IssuedAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the notbefore time for the security token. This value should be in UTC.
|
||||
/// </summary>
|
||||
public DateTime? NotBefore { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the token type.
|
||||
/// <remarks> If provided, this will be added as the value for the 'typ' header parameter. In the case of a JWE, this will be added to both the inner (JWS) and the outer token (JWE) header. By default, the value used is 'JWT'.
|
||||
/// If <see cref="AdditionalHeaderClaims"/> also contains 'typ' header claim value, it will override the TokenType provided here.
|
||||
/// This value is used only for JWT tokens and not for SAML/SAML2 tokens</remarks>
|
||||
/// </summary>
|
||||
public string TokenType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="Dictionary{TKey, TValue}"/> which contains any custom header claims that need to be added to the JWT token header.
|
||||
/// The 'alg', 'kid', 'x5t', 'enc', and 'zip' claims are added by default based on the <see cref="SigningCredentials"/>,
|
||||
/// <see cref="EncryptingCredentials"/>, and/or <see cref="CompressionAlgorithm"/> provided and SHOULD NOT be included in this dictionary as this
|
||||
/// will result in an exception being thrown.
|
||||
/// <remarks> These claims are only added to the outer header (in case of a JWE).</remarks>
|
||||
/// </summary>
|
||||
public IDictionary<string, object> AdditionalHeaderClaims { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="Dictionary{TKey, TValue}"/> which contains any custom header claims that need to be added to the inner JWT token header.
|
||||
/// The 'alg', 'kid', 'x5t', 'enc', and 'zip' claims are added by default based on the <see cref="SigningCredentials"/>,
|
||||
/// <see cref="EncryptingCredentials"/>, and/or <see cref="CompressionAlgorithm"/> provided and SHOULD NOT be included in this dictionary as this
|
||||
/// will result in an exception being thrown.
|
||||
/// <remarks>
|
||||
/// For JsonWebTokenHandler, these claims are merged with <see cref="AdditionalHeaderClaims"/> while adding to the inner JWT header.
|
||||
/// </remarks>
|
||||
/// </summary>
|
||||
public IDictionary<string, object> AdditionalInnerHeaderClaims { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="SigningCredentials"/> used to create a security token.
|
||||
/// </summary>
|
||||
public SigningCredentials SigningCredentials => _lazySigningCredentials.Value;
|
||||
#endregion SecurityTokenDescriptor
|
||||
|
||||
private readonly Lazy<RsaSecurityKey> _lazyRsaSecurityKey;
|
||||
|
||||
public SecurityKey SecurityKey => _lazyRsaSecurityKey.Value;
|
||||
|
||||
private readonly Lazy<SigningCredentials> _lazySigningCredentials;
|
||||
|
||||
/// <summary>
|
||||
/// Specifies the signature algorithm to be applied to the <see cref="SigningCredentials"/>.
|
||||
/// Default is <see cref="SecurityAlgorithms.RsaSha256"/>.
|
||||
/// </summary>
|
||||
public string SigningAlgorithm { get; init; } = SecurityAlgorithms.RsaSha256;
|
||||
|
||||
/// <summary>
|
||||
/// Optionally specifies the digest algorithm to be applied during the signing process for the <see cref="SigningCredentials"/>.
|
||||
/// If not provided, the default algorithm is used.
|
||||
/// </summary>
|
||||
public string? SigningDigest { get; init; }
|
||||
|
||||
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
|
||||
public RSATokenDescriptor()
|
||||
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
|
||||
{
|
||||
_lazyTokenValidator = new(CreatePublicKey<RSATokenValidator>);
|
||||
|
||||
_lazyRsaSecurityKey = new(() => new RsaSecurityKey(RSA));
|
||||
|
||||
_lazySigningCredentials = new(() => SigningDigest is null
|
||||
? new(SecurityKey, SigningAlgorithm)
|
||||
: new(SecurityKey, SigningAlgorithm, SigningDigest));
|
||||
}
|
||||
}
|
||||
17
DigitalData.Core.Security/RSAKey/Auth/RSATokenValidator.cs
Normal file
17
DigitalData.Core.Security/RSAKey/Auth/RSATokenValidator.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
using DigitalData.Core.Abstractions.Security.Key;
|
||||
using DigitalData.Core.Security.RSAKey.Base;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace DigitalData.Core.Security.RSAKey.Auth;
|
||||
|
||||
public class RSATokenValidator : RSAPublicKey, IAsymmetricTokenValidator
|
||||
{
|
||||
private readonly Lazy<RsaSecurityKey> _lazyRsaSecurityKey;
|
||||
|
||||
public SecurityKey SecurityKey => _lazyRsaSecurityKey.Value;
|
||||
|
||||
public RSATokenValidator()
|
||||
{
|
||||
_lazyRsaSecurityKey = new(() => new RsaSecurityKey(RSA));
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,15 @@
|
||||
using DigitalData.Core.Abstractions.Security;
|
||||
using DigitalData.Core.Abstractions.Security.Key;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DigitalData.Core.Security.RSAKey
|
||||
namespace DigitalData.Core.Security.RSAKey.Base;
|
||||
|
||||
public class RSAKeyBase : IAsymmetricKey
|
||||
{
|
||||
public class RSAKeyBase : IAsymmetricKey
|
||||
{
|
||||
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
|
||||
public virtual string Content { get; init; }
|
||||
public virtual string Content { get; init; }
|
||||
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
|
||||
|
||||
public string? Id { get; init; }
|
||||
public string? Id { get; init; }
|
||||
|
||||
protected virtual RSA RSA { get; } = RSA.Create();
|
||||
}
|
||||
protected virtual RSA RSA { get; } = RSA.Create();
|
||||
}
|
||||
54
DigitalData.Core.Security/RSAKey/Base/RSAPrivateKey.cs
Normal file
54
DigitalData.Core.Security/RSAKey/Base/RSAPrivateKey.cs
Normal file
@@ -0,0 +1,54 @@
|
||||
using DigitalData.Core.Abstractions.Security.Key;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DigitalData.Core.Security.RSAKey.Base;
|
||||
|
||||
public class RSAPrivateKey : RSAKeyBase, IAsymmetricPrivateKey, IAsymmetricKey
|
||||
{
|
||||
private string? _pem;
|
||||
|
||||
public override string Content
|
||||
{
|
||||
#pragma warning disable CS8603 // Possible null reference return.
|
||||
get => _pem;
|
||||
#pragma warning restore CS8603 // Possible null reference return.
|
||||
init
|
||||
{
|
||||
_pem = value;
|
||||
Init();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsPemNull => _pem is null;
|
||||
|
||||
public bool IsEncrypted { get; init; }
|
||||
|
||||
protected TPublicKey CreatePublicKey<TPublicKey>() where TPublicKey : RSAPublicKey, new()
|
||||
=> new() { Content = RSA.ExportRSAPublicKeyPem() };
|
||||
|
||||
private readonly Lazy<RSAPublicKey> _lazyPublicKey;
|
||||
|
||||
public IAsymmetricPublicKey PublicKey => _lazyPublicKey.Value;
|
||||
|
||||
public RSAPrivateKey()
|
||||
{
|
||||
_lazyPublicKey = new(CreatePublicKey<RSAPublicKey>);
|
||||
}
|
||||
|
||||
internal void SetPem(string pem)
|
||||
{
|
||||
_pem = pem;
|
||||
Init();
|
||||
}
|
||||
|
||||
private void Init()
|
||||
{
|
||||
if (string.IsNullOrEmpty(_pem))
|
||||
throw new InvalidOperationException($"The content of RSA private key is null or empty. Id: {Id}.");
|
||||
|
||||
if (IsEncrypted)
|
||||
RSA.ImportFromEncryptedPem(Content, Secrets.PBE_PASSWORD.AsSpan());
|
||||
else
|
||||
RSA.ImportFromPem(Content);
|
||||
}
|
||||
}
|
||||
16
DigitalData.Core.Security/RSAKey/Base/RSAPublicKey.cs
Normal file
16
DigitalData.Core.Security/RSAKey/Base/RSAPublicKey.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using DigitalData.Core.Abstractions.Security.Key;
|
||||
|
||||
namespace DigitalData.Core.Security.RSAKey.Base;
|
||||
|
||||
public class RSAPublicKey : RSAKeyBase, IAsymmetricPublicKey, IAsymmetricKey
|
||||
{
|
||||
public override string Content
|
||||
{
|
||||
get => base.Content;
|
||||
init
|
||||
{
|
||||
base.Content = value;
|
||||
RSA.ImportFromPem(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
33
DigitalData.Core.Security/RSAKey/Crypto/RSADecryptor.cs
Normal file
33
DigitalData.Core.Security/RSAKey/Crypto/RSADecryptor.cs
Normal file
@@ -0,0 +1,33 @@
|
||||
using DigitalData.Core.Abstractions.Security.Key;
|
||||
using DigitalData.Core.Security.RSAKey.Base;
|
||||
using System.Reflection;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DigitalData.Core.Security.RSAKey.Crypto;
|
||||
|
||||
public class RSADecryptor : RSAPrivateKey, IAsymmetricDecryptor
|
||||
{
|
||||
public RSAEncryptionPadding Padding { get; init; } = RSAEncryptionPadding.OaepSHA256;
|
||||
|
||||
// TODO: add as json converter to IConfigurIConfiguration.Config
|
||||
public string PaddingName
|
||||
{
|
||||
get => Padding.ToString();
|
||||
init => Padding = typeof(RSAEncryptionPadding).GetProperty(value, BindingFlags.Public | BindingFlags.Static)?.GetValue(null) as RSAEncryptionPadding ?? throw new ArgumentException($"Padding '{value}' not found.");
|
||||
}
|
||||
|
||||
public byte[] Decrypt(byte[] data) => RSA.Decrypt(data, Padding);
|
||||
|
||||
private readonly Lazy<IAsymmetricEncryptor> _lazyEncryptor;
|
||||
|
||||
public IAsymmetricEncryptor Encryptor => _lazyEncryptor.Value;
|
||||
|
||||
public RSADecryptor()
|
||||
{
|
||||
_lazyEncryptor = new(() => new RSAEncryptor()
|
||||
{
|
||||
Content = RSA.ExportRSAPublicKeyPem(),
|
||||
Padding = Padding
|
||||
});
|
||||
}
|
||||
}
|
||||
20
DigitalData.Core.Security/RSAKey/Crypto/RSAEncryptor.cs
Normal file
20
DigitalData.Core.Security/RSAKey/Crypto/RSAEncryptor.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
using DigitalData.Core.Abstractions.Security.Key;
|
||||
using DigitalData.Core.Security.RSAKey.Base;
|
||||
using System.Reflection;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DigitalData.Core.Security.RSAKey.Crypto;
|
||||
|
||||
public class RSAEncryptor : RSAPublicKey, IAsymmetricEncryptor
|
||||
{
|
||||
public RSAEncryptionPadding Padding { get; init; } = RSAEncryptionPadding.OaepSHA256;
|
||||
|
||||
// TODO: add as json converter to IConfigurIConfiguration.Config
|
||||
public string PaddingName
|
||||
{
|
||||
get => Padding.ToString();
|
||||
init => Padding = typeof(RSAEncryptionPadding).GetProperty(value, BindingFlags.Public | BindingFlags.Static)?.GetValue(null) as RSAEncryptionPadding ?? throw new ArgumentException($"Padding '{value}' not found.");
|
||||
}
|
||||
|
||||
public byte[] Encrypt(byte[] data) => RSA.Encrypt(data, Padding);
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
using DigitalData.Core.Abstractions.Security;
|
||||
using System.Reflection;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DigitalData.Core.Security.RSAKey
|
||||
{
|
||||
public class RSADecryptor : RSAPrivateKey, IAsymmetricDecryptor
|
||||
{
|
||||
public RSAEncryptionPadding Padding { get; init; } = RSAEncryptionPadding.OaepSHA256;
|
||||
|
||||
// TODO: add as json converter to IConfigurIConfiguration.Config
|
||||
public string PaddingName
|
||||
{
|
||||
get => Padding.ToString();
|
||||
init => Padding = typeof(RSAEncryptionPadding).GetProperty(value, BindingFlags.Public | BindingFlags.Static)?.GetValue(null) as RSAEncryptionPadding ?? throw new ArgumentException($"Padding '{value}' not found.");
|
||||
}
|
||||
|
||||
public byte[] Decrypt(byte[] data) => RSA.Decrypt(data, Padding);
|
||||
|
||||
private readonly Lazy<IAsymmetricEncryptor> _lazyEncryptor;
|
||||
|
||||
public IAsymmetricEncryptor Encryptor => _lazyEncryptor.Value;
|
||||
|
||||
public RSADecryptor()
|
||||
{
|
||||
_lazyEncryptor = new(() => new RSAEncryptor()
|
||||
{
|
||||
Content = RSA.ExportRSAPublicKeyPem(),
|
||||
Padding = Padding
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
using DigitalData.Core.Abstractions.Security;
|
||||
using System.Reflection;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DigitalData.Core.Security.RSAKey
|
||||
{
|
||||
public class RSAEncryptor : RSAPublicKey, IAsymmetricEncryptor
|
||||
{
|
||||
public RSAEncryptionPadding Padding { get; init; } = RSAEncryptionPadding.OaepSHA256;
|
||||
|
||||
// TODO: add as json converter to IConfigurIConfiguration.Config
|
||||
public string PaddingName
|
||||
{
|
||||
get => Padding.ToString();
|
||||
init => Padding = typeof(RSAEncryptionPadding).GetProperty(value, BindingFlags.Public | BindingFlags.Static)?.GetValue(null) as RSAEncryptionPadding ?? throw new ArgumentException($"Padding '{value}' not found.");
|
||||
}
|
||||
|
||||
public byte[] Encrypt(byte[] data) => RSA.Encrypt(data, Padding);
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
using DigitalData.Core.Abstractions.Security;
|
||||
using DigitalData.Core.Security.Config;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DigitalData.Core.Security.RSAKey
|
||||
{
|
||||
public class RSAFactory<TRSAFactoryParams> : IAsymmetricKeyFactory where TRSAFactoryParams : RSAFactoryParams
|
||||
{
|
||||
protected readonly TRSAFactoryParams _params;
|
||||
|
||||
public RSAFactory(IOptions<TRSAFactoryParams> options)
|
||||
{
|
||||
_params = options.Value;
|
||||
}
|
||||
|
||||
public string CreatePrivateKeyPem(int? keySizeInBits = null, bool encrypt = false) => encrypt
|
||||
? CreateEncryptedPrivateKeyPem(keySizeInBits: keySizeInBits)
|
||||
: RSA.Create(keySizeInBits ?? _params.KeySizeInBits).ExportRSAPrivateKeyPem();
|
||||
|
||||
public string CreateEncryptedPrivateKeyPem(
|
||||
PbeEncryptionAlgorithm? pbeEncryptionAlgorithm = null,
|
||||
HashAlgorithmName? hashAlgorithmName = null,
|
||||
int? iterationCount = null,
|
||||
int? keySizeInBits = null,
|
||||
string? password = null)
|
||||
{
|
||||
password ??= _params.PbePassword;
|
||||
|
||||
var pbeParameters = pbeEncryptionAlgorithm is null && hashAlgorithmName is null && iterationCount is null
|
||||
? new PbeParameters(
|
||||
pbeEncryptionAlgorithm ?? _params.PbeEncryptionAlgorithm,
|
||||
hashAlgorithmName ?? _params.PbeHashAlgorithm,
|
||||
iterationCount ?? _params.PbeIterationCount)
|
||||
: _params.PbeParameters;
|
||||
|
||||
var encryptedPrivateKey = RSA.Create(keySizeInBits ?? _params.KeySizeInBits).ExportEncryptedPkcs8PrivateKey(password.AsSpan(), pbeParameters);
|
||||
|
||||
var pemChars = PemEncoding.Write(_params.EncryptedPrivateKeyPemLabel, encryptedPrivateKey);
|
||||
|
||||
return new string(pemChars);
|
||||
}
|
||||
|
||||
public string CreateEncryptedPrivateKeyPem(
|
||||
PbeParameters pbeParameters,
|
||||
int? keySizeInBits = null,
|
||||
string? password = null)
|
||||
{
|
||||
password ??= _params.PbePassword;
|
||||
|
||||
var encryptedPrivateKey = RSA.Create(keySizeInBits ?? _params.KeySizeInBits).ExportEncryptedPkcs8PrivateKey(password.AsSpan(), pbeParameters);
|
||||
|
||||
var pemChars = PemEncoding.Write(_params.EncryptedPrivateKeyPemLabel, encryptedPrivateKey);
|
||||
|
||||
return new string(pemChars);
|
||||
}
|
||||
|
||||
public IAsymmetricDecryptor CreateDecryptor(string pem, string? issuer = null, string? audience = null, bool encrypt = false, RSAEncryptionPadding? padding = null) => new RSADecryptor()
|
||||
{
|
||||
Content = pem,
|
||||
IsEncrypted = encrypt,
|
||||
Padding = padding ?? RSAEncryptionPadding.OaepSHA256
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
using DigitalData.Core.Abstractions.Security;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DigitalData.Core.Security.RSAKey
|
||||
{
|
||||
public class RSAPrivateKey : RSAKeyBase, IAsymmetricPrivateKey, IAsymmetricKey
|
||||
{
|
||||
private string? _pem;
|
||||
|
||||
public override string Content
|
||||
{
|
||||
#pragma warning disable CS8603 // Possible null reference return.
|
||||
get => _pem;
|
||||
#pragma warning restore CS8603 // Possible null reference return.
|
||||
init
|
||||
{
|
||||
_pem = value;
|
||||
Init();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsPemNull => _pem is null;
|
||||
|
||||
public bool IsEncrypted { get; init; }
|
||||
|
||||
protected TPublicKey CreatePublicKey<TPublicKey>() where TPublicKey : RSAPublicKey, new()
|
||||
=> new() { Content = RSA.ExportRSAPublicKeyPem() };
|
||||
|
||||
private readonly Lazy<RSAPublicKey> _lazyPublicKey;
|
||||
|
||||
public IAsymmetricPublicKey PublicKey => _lazyPublicKey.Value;
|
||||
|
||||
public RSAPrivateKey()
|
||||
{
|
||||
_lazyPublicKey = new(CreatePublicKey<RSAPublicKey>);
|
||||
}
|
||||
|
||||
internal void SetPem(string pem)
|
||||
{
|
||||
_pem = pem;
|
||||
Init();
|
||||
}
|
||||
|
||||
private void Init()
|
||||
{
|
||||
if (string.IsNullOrEmpty(_pem))
|
||||
throw new InvalidOperationException ($"The content of RSA private key is null or empty. Id: {Id}.");
|
||||
|
||||
if (IsEncrypted)
|
||||
RSA.ImportFromEncryptedPem(Content, Secrets.PBE_PASSWORD.AsSpan());
|
||||
else
|
||||
RSA.ImportFromPem(Content);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
using DigitalData.Core.Abstractions.Security;
|
||||
|
||||
namespace DigitalData.Core.Security.RSAKey
|
||||
{
|
||||
public class RSAPublicKey : RSAKeyBase, IAsymmetricPublicKey, IAsymmetricKey
|
||||
{
|
||||
public override string Content
|
||||
{
|
||||
get => base.Content;
|
||||
init
|
||||
{
|
||||
base.Content = value;
|
||||
RSA.ImportFromPem(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
using DigitalData.Core.Abstractions.Security;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace DigitalData.Core.Security.RSAKey
|
||||
{
|
||||
/// <summary>
|
||||
/// Contains some information which used to create a security token. Designed to abstract <see cref="SecurityTokenDescriptor"/>
|
||||
/// </summary>
|
||||
public class RSATokenDescriptor : RSAPrivateKey, IAsymmetricTokenDescriptor
|
||||
{
|
||||
private readonly Lazy<RSATokenValidator> _lazyTokenValidator;
|
||||
|
||||
public IAsymmetricTokenValidator Validator => _lazyTokenValidator.Value;
|
||||
|
||||
public required TimeSpan Lifetime { get; init; }
|
||||
|
||||
#region SecurityTokenDescriptor Map
|
||||
/// <summary>
|
||||
/// Gets or sets the value of the 'audience' claim.
|
||||
/// </summary>
|
||||
public required string Audience { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Defines the compression algorithm that will be used to compress the JWT token payload.
|
||||
/// </summary>
|
||||
public string CompressionAlgorithm { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="EncryptingCredentials"/> used to create a encrypted security token.
|
||||
/// </summary>
|
||||
public EncryptingCredentials EncryptingCredentials { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the value of the 'expiration' claim. This value should be in UTC.
|
||||
/// The expiration time is the sum of DateTime.Now and LifeTime.
|
||||
/// </summary>
|
||||
public DateTime? Expires => DateTime.Now.AddTicks(Lifetime.Ticks);
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the issuer of this <see cref="SecurityTokenDescriptor"/>.
|
||||
/// </summary>
|
||||
public required string Issuer { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time the security token was issued. This value should be in UTC.
|
||||
/// </summary>
|
||||
public DateTime? IssuedAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the notbefore time for the security token. This value should be in UTC.
|
||||
/// </summary>
|
||||
public DateTime? NotBefore { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the token type.
|
||||
/// <remarks> If provided, this will be added as the value for the 'typ' header parameter. In the case of a JWE, this will be added to both the inner (JWS) and the outer token (JWE) header. By default, the value used is 'JWT'.
|
||||
/// If <see cref="AdditionalHeaderClaims"/> also contains 'typ' header claim value, it will override the TokenType provided here.
|
||||
/// This value is used only for JWT tokens and not for SAML/SAML2 tokens</remarks>
|
||||
/// </summary>
|
||||
public string TokenType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="Dictionary{TKey, TValue}"/> which contains any custom header claims that need to be added to the JWT token header.
|
||||
/// The 'alg', 'kid', 'x5t', 'enc', and 'zip' claims are added by default based on the <see cref="SigningCredentials"/>,
|
||||
/// <see cref="EncryptingCredentials"/>, and/or <see cref="CompressionAlgorithm"/> provided and SHOULD NOT be included in this dictionary as this
|
||||
/// will result in an exception being thrown.
|
||||
/// <remarks> These claims are only added to the outer header (in case of a JWE).</remarks>
|
||||
/// </summary>
|
||||
public IDictionary<string, object> AdditionalHeaderClaims { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="Dictionary{TKey, TValue}"/> which contains any custom header claims that need to be added to the inner JWT token header.
|
||||
/// The 'alg', 'kid', 'x5t', 'enc', and 'zip' claims are added by default based on the <see cref="SigningCredentials"/>,
|
||||
/// <see cref="EncryptingCredentials"/>, and/or <see cref="CompressionAlgorithm"/> provided and SHOULD NOT be included in this dictionary as this
|
||||
/// will result in an exception being thrown.
|
||||
/// <remarks>
|
||||
/// For JsonWebTokenHandler, these claims are merged with <see cref="AdditionalHeaderClaims"/> while adding to the inner JWT header.
|
||||
/// </remarks>
|
||||
/// </summary>
|
||||
public IDictionary<string, object> AdditionalInnerHeaderClaims { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="SigningCredentials"/> used to create a security token.
|
||||
/// </summary>
|
||||
public SigningCredentials SigningCredentials => _lazySigningCredentials.Value;
|
||||
#endregion SecurityTokenDescriptor
|
||||
|
||||
private readonly Lazy<RsaSecurityKey> _lazyRsaSecurityKey;
|
||||
|
||||
public SecurityKey SecurityKey => _lazyRsaSecurityKey.Value;
|
||||
|
||||
private readonly Lazy<SigningCredentials> _lazySigningCredentials;
|
||||
|
||||
/// <summary>
|
||||
/// Specifies the signature algorithm to be applied to the <see cref="SigningCredentials"/>.
|
||||
/// Default is <see cref="SecurityAlgorithms.RsaSha256"/>.
|
||||
/// </summary>
|
||||
public string SigningAlgorithm { get; init; } = SecurityAlgorithms.RsaSha256;
|
||||
|
||||
/// <summary>
|
||||
/// Optionally specifies the digest algorithm to be applied during the signing process for the <see cref="SigningCredentials"/>.
|
||||
/// If not provided, the default algorithm is used.
|
||||
/// </summary>
|
||||
public string? SigningDigest { get; init; }
|
||||
|
||||
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
|
||||
public RSATokenDescriptor()
|
||||
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
|
||||
{
|
||||
_lazyTokenValidator = new(CreatePublicKey<RSATokenValidator>);
|
||||
|
||||
_lazyRsaSecurityKey = new(() => new RsaSecurityKey(RSA));
|
||||
|
||||
_lazySigningCredentials = new(() => SigningDigest is null
|
||||
? new(SecurityKey, SigningAlgorithm)
|
||||
: new(SecurityKey, SigningAlgorithm, SigningDigest));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
using DigitalData.Core.Abstractions.Security;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace DigitalData.Core.Security.RSAKey
|
||||
{
|
||||
public class RSATokenValidator : RSAPublicKey, IAsymmetricTokenValidator
|
||||
{
|
||||
private readonly Lazy<RsaSecurityKey> _lazyRsaSecurityKey;
|
||||
|
||||
public SecurityKey SecurityKey => _lazyRsaSecurityKey.Value;
|
||||
|
||||
public RSATokenValidator()
|
||||
{
|
||||
_lazyRsaSecurityKey = new(() => new RsaSecurityKey(RSA));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,13 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace DigitalData.Core.Security
|
||||
namespace DigitalData.Core.Security;
|
||||
|
||||
public static class Secrets
|
||||
{
|
||||
public static class Secrets
|
||||
{
|
||||
public static readonly DateTime CreationDate = new (2024, 11, 19);
|
||||
public static readonly DateTime CreationDate = new (2024, 11, 19);
|
||||
|
||||
public static readonly Version Version = new (1, 0);
|
||||
public static readonly Version Version = new (1, 0);
|
||||
|
||||
[JsonIgnore]
|
||||
internal static readonly string PBE_PASSWORD = "9mk@i/$QY&Mw@_--dI^ahlXpNKEtv_U-,V-46b19_-Z6-U_*89_n1_-5-r-_+_$_IY_mYQl-";
|
||||
}
|
||||
[JsonIgnore]
|
||||
internal static readonly string PBE_PASSWORD = "9mk@i/$QY&Mw@_--dI^ahlXpNKEtv_U-,V-46b19_-Z6-U_*89_n1_-5-r-_+_$_IY_mYQl-";
|
||||
}
|
||||
42
DigitalData.Core.Security/Services/JwtSignatureHandler.cs
Normal file
42
DigitalData.Core.Security/Services/JwtSignatureHandler.cs
Normal file
@@ -0,0 +1,42 @@
|
||||
using AutoMapper;
|
||||
using DigitalData.Core.Abstractions.Security.Extensions;
|
||||
using DigitalData.Core.Abstractions.Security.Key;
|
||||
using DigitalData.Core.Abstractions.Security.Services;
|
||||
using DigitalData.Core.Security.Config;
|
||||
using DigitalData.Core.Security.Extensions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
|
||||
namespace DigitalData.Core.Security.Services;
|
||||
|
||||
public class JwtSignatureHandler<TPrincipal> : JwtSecurityTokenHandler, IJwtSignatureHandler<TPrincipal>
|
||||
{
|
||||
private readonly ClaimDescriptor<TPrincipal> _claimDescriptor;
|
||||
|
||||
private readonly IMapper _mapper;
|
||||
|
||||
private readonly IAsymmetricKeyPool _cryptoFactory;
|
||||
|
||||
public JwtSignatureHandler(IOptions<ClaimDescriptor<TPrincipal>> claimDescriptorOptions, IMapper mapper, IAsymmetricKeyPool cryptoFactory)
|
||||
{
|
||||
_claimDescriptor = claimDescriptorOptions.Value;
|
||||
_mapper = mapper;
|
||||
_cryptoFactory = cryptoFactory;
|
||||
}
|
||||
|
||||
public SecurityToken CreateToken(TPrincipal subject, IAsymmetricTokenDescriptor descriptor)
|
||||
{
|
||||
var sDescriptor = _mapper.Map(descriptor);
|
||||
sDescriptor.Claims = _claimDescriptor.CreateClaims?.Invoke(subject);
|
||||
sDescriptor.Subject = _claimDescriptor.CreateSubject?.Invoke(subject);
|
||||
return CreateToken(sDescriptor);
|
||||
}
|
||||
|
||||
public SecurityToken CreateToken(TPrincipal subject, string issuer, string audience)
|
||||
{
|
||||
var descriptor = _cryptoFactory.TokenDescriptors.Get(issuer: issuer, audience: audience)
|
||||
?? throw new InvalidOperationException($"No or multiple token description found for issuer '{issuer}' and audience '{audience}'.");
|
||||
return CreateToken(subject: subject, descriptor: descriptor);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using DigitalData.Core.Security.Config;
|
||||
using DigitalData.Core.Security.RSAKey;
|
||||
using DigitalData.Core.Security.Extensions;
|
||||
using DigitalData.Core.Security.RSAKey.Auth;
|
||||
using DigitalData.Core.Security.RSAKey.Base;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
@@ -8,11 +10,11 @@ namespace DigitalData.Core.Security.Services;
|
||||
|
||||
public class PemFileInitalizer : BackgroundService
|
||||
{
|
||||
private readonly CryptoFactoryParams _factoryParams;
|
||||
private readonly RSAParams _factoryParams;
|
||||
|
||||
private readonly ILogger<PemFileInitalizer>? _logger;
|
||||
private readonly ILogger<PemFileInitalizer> _logger;
|
||||
|
||||
public PemFileInitalizer(IOptions<CryptoFactoryParams> factoryParamsOptions, ILogger<PemFileInitalizer>? logger = null)
|
||||
public PemFileInitalizer(IOptions<RSAParams> factoryParamsOptions, ILogger<PemFileInitalizer> logger)
|
||||
{
|
||||
_factoryParams = factoryParamsOptions.Value;
|
||||
_logger = logger;
|
||||
@@ -20,9 +22,7 @@ public class PemFileInitalizer : BackgroundService
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
if (_logger is null)
|
||||
await InitPemFiles(stoppingToken);
|
||||
else try
|
||||
try
|
||||
{
|
||||
await InitPemFiles(stoppingToken);
|
||||
}
|
||||
@@ -72,8 +72,8 @@ public class PemFileInitalizer : BackgroundService
|
||||
else
|
||||
{
|
||||
var pem = privateKey.IsEncrypted
|
||||
? Instance.RSAFactory.CreateEncryptedPrivateKeyPem(pbeParameters: _factoryParams.PbeParameters, keySizeInBits: _factoryParams.KeySizeInBits, password: Secrets.PBE_PASSWORD)
|
||||
: Instance.RSAFactory.CreatePrivateKeyPem(keySizeInBits: _factoryParams.KeySizeInBits);
|
||||
? RSAFactory.Static.CreateEncryptedPrivateKeyPem(pbeParameters: _factoryParams.PbeParameters, keySizeInBits: _factoryParams.KeySizeInBits, password: Secrets.PBE_PASSWORD)
|
||||
: RSAFactory.Static.CreatePrivateKeyPem(keySizeInBits: _factoryParams.KeySizeInBits);
|
||||
|
||||
privateKey.SetPem(pem);
|
||||
|
||||
|
||||
58
DigitalData.Core.Security/Services/RSAFactory.cs
Normal file
58
DigitalData.Core.Security/Services/RSAFactory.cs
Normal file
@@ -0,0 +1,58 @@
|
||||
using DigitalData.Core.Abstractions.Security.Key;
|
||||
using DigitalData.Core.Abstractions.Security.Services;
|
||||
using DigitalData.Core.Security.Config;
|
||||
using DigitalData.Core.Security.RSAKey.Crypto;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace DigitalData.Core.Security.Services;
|
||||
|
||||
public class RSAFactory : IAsymmetricKeyFactory
|
||||
{
|
||||
public static readonly RSAFactory Static = new();
|
||||
|
||||
public string CreatePrivateKeyPem(int? keySizeInBits = null, bool encrypt = false) => encrypt
|
||||
? CreateEncryptedPrivateKeyPem(keySizeInBits: keySizeInBits)
|
||||
: RSA.Create(keySizeInBits ?? RSAParams.Default.KeySizeInBits).ExportRSAPrivateKeyPem();
|
||||
|
||||
public string CreateEncryptedPrivateKeyPem(
|
||||
PbeEncryptionAlgorithm? pbeEncryptionAlgorithm = null,
|
||||
HashAlgorithmName? hashAlgorithmName = null,
|
||||
int? iterationCount = null,
|
||||
int? keySizeInBits = null,
|
||||
string? password = null)
|
||||
{
|
||||
password ??= RSAParams.Default.PbePassword;
|
||||
|
||||
var pbeParameters = new PbeParameters(
|
||||
pbeEncryptionAlgorithm ?? RSAParams.Default.PbeEncryptionAlgorithm,
|
||||
hashAlgorithmName ?? RSAParams.Default.PbeHashAlgorithm,
|
||||
iterationCount ?? RSAParams.Default.PbeIterationCount);
|
||||
|
||||
var encryptedPrivateKey = RSA.Create(keySizeInBits ?? RSAParams.Default.KeySizeInBits).ExportEncryptedPkcs8PrivateKey(password.AsSpan(), pbeParameters);
|
||||
|
||||
var pemChars = PemEncoding.Write(RSAParams.Default.EncryptedPrivateKeyPemLabel, encryptedPrivateKey);
|
||||
|
||||
return new string(pemChars);
|
||||
}
|
||||
|
||||
public string CreateEncryptedPrivateKeyPem(
|
||||
PbeParameters pbeParameters,
|
||||
int? keySizeInBits = null,
|
||||
string? password = null)
|
||||
{
|
||||
password ??= RSAParams.Default.PbePassword;
|
||||
|
||||
var encryptedPrivateKey = RSA.Create(keySizeInBits ?? RSAParams.Default.KeySizeInBits).ExportEncryptedPkcs8PrivateKey(password.AsSpan(), pbeParameters);
|
||||
|
||||
var pemChars = PemEncoding.Write(RSAParams.Default.EncryptedPrivateKeyPemLabel, encryptedPrivateKey);
|
||||
|
||||
return new string(pemChars);
|
||||
}
|
||||
|
||||
public IAsymmetricDecryptor CreateDecryptor(string pem, string? issuer = null, string? audience = null, bool encrypt = false, RSAEncryptionPadding? padding = null) => new RSADecryptor()
|
||||
{
|
||||
Content = pem,
|
||||
IsEncrypted = encrypt,
|
||||
Padding = padding ?? RSAEncryptionPadding.OaepSHA256
|
||||
};
|
||||
}
|
||||
41
DigitalData.Core.Security/Services/RSAPool.cs
Normal file
41
DigitalData.Core.Security/Services/RSAPool.cs
Normal file
@@ -0,0 +1,41 @@
|
||||
using DigitalData.Core.Abstractions.Security.Key;
|
||||
using DigitalData.Core.Abstractions.Security.Services;
|
||||
using DigitalData.Core.Security.Config;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace DigitalData.Core.Security.Services;
|
||||
|
||||
public class RSAPool : RSAFactory, IAsymmetricKeyPool, IAsymmetricKeyFactory
|
||||
{
|
||||
private readonly RSAParams _params;
|
||||
|
||||
public IEnumerable<IAsymmetricDecryptor> Decryptors { get; }
|
||||
|
||||
/// <summary>
|
||||
/// It is a separate decryptor for permanently stored encrypted data. It is assigned to the first Default decryptor by default.
|
||||
/// </summary>
|
||||
public IAsymmetricDecryptor VaultDecryptor { get; }
|
||||
|
||||
public IEnumerable<IAsymmetricTokenDescriptor> TokenDescriptors { get; init; } = new List<IAsymmetricTokenDescriptor>();
|
||||
|
||||
public RSAPool(IOptions<RSAParams> cryptoFactoryParamsOptions, ILogger<RSAPool>? logger = null)
|
||||
{
|
||||
_params = cryptoFactoryParamsOptions.Value;
|
||||
|
||||
logger?.LogInformation("Core.Secrets version: {Version}, Created on: {CreationDate}.", Secrets.Version, Secrets.CreationDate.ToString("dd.MM.yyyy"));
|
||||
|
||||
if (!_params.Decryptors.Any())
|
||||
throw new InvalidOperationException(
|
||||
"Any decryptor is not found. Ensure that at least one decryptor is configured in the provided parameters. " +
|
||||
"This issue typically arises if the configuration for decryptors is incomplete or missing. " +
|
||||
"Check the 'Decryptors' collection in the configuration and verify that it contains valid entries."
|
||||
);
|
||||
|
||||
Decryptors = _params.Decryptors;
|
||||
|
||||
TokenDescriptors = _params.TokenDescriptors;
|
||||
|
||||
VaultDecryptor = _params.VaultDecryptor ?? Decryptors.First();
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DigitalData.Core.Terminal",
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DigitalData.Core.Tests.API", "DigitalData.Core.Tests.API\DigitalData.Core.Tests.API.csproj", "{9BC2DEC5-E89D-48CC-9A51-4D94496EE4A6}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Security", "Security", "{72CBAFBA-55CC-49C9-A484-F8F4550054CB}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DigitalData.Core.Abstractions.Security", "DigitalData.Core.Abstractions.Security\DigitalData.Core.Abstractions.Security.csproj", "{C9266749-9504-4EA9-938F-F083357B60B7}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -80,10 +84,18 @@ Global
|
||||
{9BC2DEC5-E89D-48CC-9A51-4D94496EE4A6}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{9BC2DEC5-E89D-48CC-9A51-4D94496EE4A6}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{9BC2DEC5-E89D-48CC-9A51-4D94496EE4A6}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{C9266749-9504-4EA9-938F-F083357B60B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{C9266749-9504-4EA9-938F-F083357B60B7}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{C9266749-9504-4EA9-938F-F083357B60B7}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{C9266749-9504-4EA9-938F-F083357B60B7}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{47D80C65-74A2-4EB8-96A5-D571A9108FB3} = {72CBAFBA-55CC-49C9-A484-F8F4550054CB}
|
||||
{C9266749-9504-4EA9-938F-F083357B60B7} = {72CBAFBA-55CC-49C9-A484-F8F4550054CB}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {8E2C3187-F848-493A-9E79-56D20DDCAC94}
|
||||
EndGlobalSection
|
||||
|
||||
Reference in New Issue
Block a user