Compare commits

..

No commits in common. "095b66f6f3a9d22e367b6decbc7736f4be12bb7c" and "ec7e2605114e105e7dc3e2d58b6355e2611d5b64" have entirely different histories.

9 changed files with 310 additions and 150 deletions

View File

@ -1,15 +1,15 @@
using DotBased.AspNet.Authority.Models;
using DotBased.AspNet.Authority.Models.Authority; using DotBased.AspNet.Authority.Models.Authority;
using DotBased.AspNet.Authority.Repositories; using DotBased.AspNet.Authority.Repositories;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace DotBased.AspNet.Authority.EFCore.Repositories; namespace DotBased.AspNet.Authority.EFCore.Repositories;
public class AttributeRepository(IDbContextFactory<AuthorityContext> contextFactory, ILogger<AttributeRepository> logger) : RepositoryBase, IAttributeRepository public class AttributeRepository(IDbContextFactory<AuthorityContext> contextFactory) : RepositoryBase, IAttributeRepository
{ {
public async Task<QueryItems<AuthorityAttributeItem>> GetAttributesAsync(int limit = 20, int offset = 0, string search = "", public async Task<ListResultOld<AuthorityAttributeItem>> GetAttributesAsync(int limit = 20, int offset = 0, string search = "",
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
{
try
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var query = context.Attributes.AsQueryable(); var query = context.Attributes.AsQueryable();
@ -25,62 +25,90 @@ public class AttributeRepository(IDbContextFactory<AuthorityContext> contextFact
AttributeKey = a.AttributeKey, AttributeKey = a.AttributeKey,
AttributeValue = a.AttributeValue AttributeValue = a.AttributeValue
}).ToListAsync(cancellationToken); }).ToListAsync(cancellationToken);
return QueryItems<AuthorityAttributeItem>.Create(select, total, limit, offset); return ListResultOld<AuthorityAttributeItem>.Ok(select, total, limit, offset);
}
catch (Exception e)
{
return HandleExceptionListResult<AuthorityAttributeItem>("Failed to get attributes", e);
}
} }
public async Task<AuthorityAttribute?> GetAttributeByKeyAsync(string key, CancellationToken cancellationToken = default) public async Task<ResultOld<AuthorityAttribute>> GetAttributeByKeyAsync(string key, CancellationToken cancellationToken = default)
{
try
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
return await context.Attributes.FirstOrDefaultAsync(a => a.AttributeKey == key, cancellationToken); var attribute = await context.Attributes.FirstOrDefaultAsync(a => a.AttributeKey == key, cancellationToken);
return attribute == null ? ResultOld<AuthorityAttribute>.Failed("Attribute not found") : ResultOld<AuthorityAttribute>.Ok(attribute);
}
catch (Exception e)
{
return HandleExceptionResult<AuthorityAttribute>("Failed to get attribute by id", e);
}
} }
public async Task<AuthorityAttribute?> CreateAttributeAsync(AuthorityAttribute attribute, public async Task<ResultOld<AuthorityAttribute>> CreateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default)
CancellationToken cancellationToken = default) {
try
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (string.IsNullOrWhiteSpace(attribute.AttributeKey) || attribute.ForeignKey == Guid.Empty) if (string.IsNullOrWhiteSpace(attribute.AttributeKey) || attribute.ForeignKey == Guid.Empty)
{ {
throw new Exception($"Attribute {attribute.AttributeKey} not found"); return ResultOld<AuthorityAttribute>.Failed("Attribute key and/or bound id is empty");
} }
var entry = context.Attributes.Add(attribute); var entry = context.Attributes.Add(attribute);
var saveResult = await context.SaveChangesAsync(cancellationToken); var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0 ? entry.Entity : null; return saveResult <= 0 ? ResultOld<AuthorityAttribute>.Failed("Failed to create attribute") : ResultOld<AuthorityAttribute>.Ok(entry.Entity);
}
catch (Exception e)
{
return HandleExceptionResult<AuthorityAttribute>("Failed to create attribute", e);
}
} }
public async Task<AuthorityAttribute?> UpdateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default) public async Task<ResultOld<AuthorityAttribute>> UpdateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default)
{
try
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var currentAttribute = await context.Attributes.FirstOrDefaultAsync(a => a.AttributeKey == attribute.AttributeKey, cancellationToken); var currentAttribute = await context.Attributes.FirstOrDefaultAsync(a => a.AttributeKey == attribute.AttributeKey, cancellationToken);
if (currentAttribute == null) if (currentAttribute == null)
{ {
return null; return ResultOld<AuthorityAttribute>.Failed("Attribute not found");
} }
if (currentAttribute.Version != attribute.Version) if (currentAttribute.Version != attribute.Version)
{ {
logger.LogError("Attribute version validation failed for attribute {attribute}", currentAttribute.AttributeKey); return ResultOld<AuthorityAttribute>.Failed("Attribute version doesn't match");
return null;
} }
var entry = context.Attributes.Update(currentAttribute); var entry = context.Attributes.Update(currentAttribute);
var saveResult = await context.SaveChangesAsync(cancellationToken); var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0 ? entry.Entity : null; return saveResult <= 0 ? ResultOld<AuthorityAttribute>.Failed("Failed to update attribute") : ResultOld<AuthorityAttribute>.Ok(entry.Entity);
}
catch (Exception e)
{
return HandleExceptionResult<AuthorityAttribute>("Failed to update attribute", e);
}
} }
public async Task<bool> DeleteAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default) public async Task<ResultOld> DeleteAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default)
{
try
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var currentAttribute = await context.Attributes.FirstOrDefaultAsync(a => a.AttributeKey == attribute.AttributeKey, cancellationToken); var currentAttribute = await context.Attributes.FirstOrDefaultAsync(a => a.AttributeKey == attribute.AttributeKey, cancellationToken);
if (currentAttribute == null) if (currentAttribute == null)
{ {
logger.LogError("Attribute not found."); return ResultOld.Failed("Attribute not found");
return false;
} }
context.Attributes.Remove(currentAttribute); context.Attributes.Remove(currentAttribute);
var saveResult = await context.SaveChangesAsync(cancellationToken); var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0; return saveResult <= 0 ? ResultOld.Failed("Failed to delete attribute") : ResultOld.Ok();
}
catch (Exception e)
{
return HandleException("Failed to delete attribute", e);
}
} }
} }

View File

@ -1,14 +1,14 @@
using DotBased.AspNet.Authority.Models;
using DotBased.AspNet.Authority.Models.Authority; using DotBased.AspNet.Authority.Models.Authority;
using DotBased.AspNet.Authority.Repositories; using DotBased.AspNet.Authority.Repositories;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace DotBased.AspNet.Authority.EFCore.Repositories; namespace DotBased.AspNet.Authority.EFCore.Repositories;
public class GroupRepository(IDbContextFactory<AuthorityContext> contextFactory, ILogger<GroupRepository> logger) : RepositoryBase, IGroupRepository public class GroupRepository(IDbContextFactory<AuthorityContext> contextFactory) : RepositoryBase, IGroupRepository
{ {
public async Task<QueryItems<AuthorityGroupItem>> GetGroupsAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default) public async Task<ListResultOld<AuthorityGroupItem>> GetGroupsAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
{
try
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var query = context.Groups.AsQueryable(); var query = context.Groups.AsQueryable();
@ -22,73 +22,109 @@ public class GroupRepository(IDbContextFactory<AuthorityContext> contextFactory,
Id = g.Id, Id = g.Id,
Name = g.Name Name = g.Name
}).ToListAsync(cancellationToken); }).ToListAsync(cancellationToken);
return QueryItems<AuthorityGroupItem>.Create(select, total, limit, offset); return ListResultOld<AuthorityGroupItem>.Ok(select, total, limit, offset);
}
catch (Exception e)
{
return HandleExceptionListResult<AuthorityGroupItem>("Failed to get Groups", e);
}
} }
public async Task<AuthorityGroup?> GetGroupByIdAsync(string id, CancellationToken cancellationToken = default) public async Task<ResultOld<AuthorityGroup>> GetGroupByIdAsync(string id, CancellationToken cancellationToken = default)
{
try
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (!Guid.TryParse(id, out var groupId)) if (!Guid.TryParse(id, out var groupId))
{ {
throw new Exception($"Invalid group id: {id}"); return ResultOld<AuthorityGroup>.Failed("Invalid group id");
}
var group = await context.Groups.Where(g => g.Id == groupId).Include(g => g.Attributes).FirstOrDefaultAsync(cancellationToken: cancellationToken);
return ResultOld<AuthorityGroup>.HandleResult(group, "Group not found");
}
catch (Exception e)
{
return HandleExceptionResult<AuthorityGroup>("Failed to get Group", e);
}
} }
return await context.Groups.Where(g => g.Id == groupId).Include(g => g.Attributes).FirstOrDefaultAsync(cancellationToken: cancellationToken); public async Task<ListResultOld<AuthorityGroup>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default)
} {
try
public async Task<List<AuthorityGroup>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default)
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var userJoinGroups = context.UserGroups.Where(ug => ug.UserId == user.Id).Select(ug => ug.GroupId); var userJoinGroups = context.UserGroups.Where(ug => ug.UserId == user.Id).Select(ug => ug.GroupId);
var userGroups = context.Groups.Where(g => userJoinGroups.Contains(g.Id)); var userGroups = context.Groups.Where(g => userJoinGroups.Contains(g.Id));
return userGroups.ToList(); return ListResultOld<AuthorityGroup>.Ok(userGroups, userGroups.Count());
}
catch (Exception e)
{
return HandleExceptionListResult<AuthorityGroup>("Failed to get Groups", e);
}
} }
public async Task<AuthorityGroup?> CreateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default) public async Task<ResultOld<AuthorityGroup>> CreateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default)
{
try
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (group.Id == Guid.Empty) if (group.Id == Guid.Empty)
{ {
throw new Exception($"Invalid group id: {group.Id}"); return ResultOld<AuthorityGroup>.Failed("Id cannot be empty.");
} }
var entry = context.Groups.Add(group); var entry = context.Groups.Add(group);
var saveResult = await context.SaveChangesAsync(cancellationToken); var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0 ? entry.Entity : null; return saveResult <= 0 ? ResultOld<AuthorityGroup>.Failed("Failed to create group.") : ResultOld<AuthorityGroup>.Ok(entry.Entity);
}
catch (Exception e)
{
return HandleExceptionResult<AuthorityGroup>("Failed to create group!", e);
}
} }
public async Task<AuthorityGroup?> UpdateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default) public async Task<ResultOld<AuthorityGroup>> UpdateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default)
{
try
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var currentGroup = await context.Groups.FirstOrDefaultAsync(g => g.Id == group.Id ,cancellationToken); var currentGroup = await context.Groups.FirstOrDefaultAsync(g => g.Id == group.Id ,cancellationToken);
if (currentGroup == null) if (currentGroup == null)
{ {
logger.LogError("Group with id {groupId} not found.", group.Id); return ResultOld<AuthorityGroup>.Failed("Group not found.");
return null;
} }
if (currentGroup.Version != group.Version) if (currentGroup.Version != group.Version)
{ {
logger.LogError("Group version validation failed."); return ResultOld<AuthorityGroup>.Failed("Group version does not match, version validation failed!");
return null;
} }
var entry = context.Groups.Update(group); var entry = context.Groups.Update(group);
var saveResult = await context.SaveChangesAsync(cancellationToken); var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0 ? entry.Entity : null; return saveResult <= 0 ? ResultOld<AuthorityGroup>.Failed("Failed to update group.") : ResultOld<AuthorityGroup>.Ok(entry.Entity);
}
catch (Exception e)
{
return HandleExceptionResult<AuthorityGroup>("Failed to update group!", e);
}
} }
public async Task<bool> DeleteGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default) public async Task<ResultOld> DeleteGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default)
{
try
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var currentGroup = await context.Groups.FirstOrDefaultAsync(g => g.Id == group.Id, cancellationToken); var currentGroup = await context.Groups.FirstOrDefaultAsync(g => g.Id == group.Id, cancellationToken);
if (currentGroup == null) if (currentGroup == null)
{ {
logger.LogError("Group with id {groupId} not found.", group.Id); return ResultOld.Failed("Group not found, cannot delete group!");
return false;
} }
context.Groups.Remove(currentGroup); context.Groups.Remove(currentGroup);
var saveResult = await context.SaveChangesAsync(cancellationToken); var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0; return saveResult <= 0 ? ResultOld.Failed("Failed to delete group.") : ResultOld.Ok();
}
catch (Exception e)
{
return HandleException("Failed to delete group!", e);
}
} }
} }

View File

@ -2,5 +2,18 @@ namespace DotBased.AspNet.Authority.EFCore.Repositories;
public abstract class RepositoryBase public abstract class RepositoryBase
{ {
protected ResultOld<T> HandleExceptionResult<T>(string message, Exception ex) => new(HandleException(message, ex));
protected ListResultOld<T> HandleExceptionListResult<T>(string message, Exception ex) =>
new(HandleException(message, ex));
protected ResultOld HandleException(string message, Exception ex)
{
if (ex is OperationCanceledException oce)
{
return ResultOld.Failed("Operation cancelled.", oce);
}
return ResultOld.Failed(message, ex);
}
} }

View File

@ -1,19 +1,11 @@
using DotBased.AspNet.Authority.Models.Authority; using DotBased.AspNet.Authority.Models.Authority;
using DotBased.Monads;
namespace DotBased.AspNet.Authority.Managers; namespace DotBased.AspNet.Authority.Managers;
public partial class AuthorityManager public partial class AuthorityManager
{ {
public async Task<Result<List<AuthorityGroup>>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default) public async Task<ListResultOld<AuthorityGroup>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default)
{
try
{ {
return await GroupRepository.GetUserGroupsAsync(user, cancellationToken); return await GroupRepository.GetUserGroupsAsync(user, cancellationToken);
} }
catch (Exception e)
{
return e;
}
}
} }

View File

@ -109,9 +109,9 @@ public partial class AuthorityManager
var searchIds = new List<Guid> { user.Id }; var searchIds = new List<Guid> { user.Id };
var usrGroups = await GetUserGroupsAsync(user, cancellationToken); var usrGroups = await GetUserGroupsAsync(user, cancellationToken);
if (usrGroups.IsSuccess) if (usrGroups.Success)
{ {
searchIds.AddRange(usrGroups.Value.Select(g => g.Id).ToList()); searchIds.AddRange(usrGroups.Items.Select(g => g.Id).ToList());
} }
var linkedRolesResult = await RoleRepository.GetLinkedRolesAsync(searchIds, cancellationToken); var linkedRolesResult = await RoleRepository.GetLinkedRolesAsync(searchIds, cancellationToken);

View File

@ -1,13 +1,12 @@
using DotBased.AspNet.Authority.Models;
using DotBased.AspNet.Authority.Models.Authority; using DotBased.AspNet.Authority.Models.Authority;
namespace DotBased.AspNet.Authority.Repositories; namespace DotBased.AspNet.Authority.Repositories;
public interface IAttributeRepository public interface IAttributeRepository
{ {
public Task<QueryItems<AuthorityAttributeItem>> GetAttributesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default); public Task<ListResultOld<AuthorityAttributeItem>> GetAttributesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
public Task<AuthorityAttribute?> GetAttributeByKeyAsync(string id, CancellationToken cancellationToken = default); public Task<ResultOld<AuthorityAttribute>> GetAttributeByKeyAsync(string id, CancellationToken cancellationToken = default);
public Task<AuthorityAttribute?> CreateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default); public Task<ResultOld<AuthorityAttribute>> CreateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default);
public Task<AuthorityAttribute?> UpdateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default); public Task<ResultOld<AuthorityAttribute>> UpdateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default);
public Task<bool> DeleteAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default); public Task<ResultOld> DeleteAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default);
} }

View File

@ -1,14 +1,13 @@
using DotBased.AspNet.Authority.Models;
using DotBased.AspNet.Authority.Models.Authority; using DotBased.AspNet.Authority.Models.Authority;
namespace DotBased.AspNet.Authority.Repositories; namespace DotBased.AspNet.Authority.Repositories;
public interface IGroupRepository public interface IGroupRepository
{ {
public Task<QueryItems<AuthorityGroupItem>> GetGroupsAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default); public Task<ListResultOld<AuthorityGroupItem>> GetGroupsAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
public Task<AuthorityGroup?> GetGroupByIdAsync(string id, CancellationToken cancellationToken = default); public Task<ResultOld<AuthorityGroup>> GetGroupByIdAsync(string id, CancellationToken cancellationToken = default);
public Task<List<AuthorityGroup>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default); public Task<ListResultOld<AuthorityGroup>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default);
public Task<AuthorityGroup?> CreateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default); public Task<ResultOld<AuthorityGroup>> CreateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
public Task<AuthorityGroup?> UpdateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default); public Task<ResultOld<AuthorityGroup>> UpdateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
public Task<bool> DeleteGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default); public Task<ResultOld> DeleteGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
} }

94
DotBased/ResultOld.cs Executable file
View File

@ -0,0 +1,94 @@
namespace DotBased;
/// <summary>
/// Simple result class for returning a result state or a message and an exception.
/// </summary>
public class ResultOld
{
public ResultOld(bool success, string message, Exception? exception)
{
Success = success;
Message = message;
Exception = exception;
}
public ResultOld(ResultOld bObj)
{
Success = bObj.Success;
Message = bObj.Message;
Exception = bObj.Exception;
}
public bool Success { get; set; }
public string Message { get; set; }
public Exception? Exception { get; set; }
public static ResultOld Ok() => new(true, string.Empty, null);
public static ResultOld Failed(string message, Exception? exception = null) => new(false, message, exception);
}
public class ResultOld<TValue> : ResultOld
{
public ResultOld(bool success, string message, TValue? value, Exception? exception) : base(success, message, exception)
{
Value = value;
}
public ResultOld(ResultOld bObj) : base(bObj)
{
}
public TValue? Value { get; set; }
public static ResultOld<TValue> Ok(TValue value) => new(true, string.Empty, value, null);
public new static ResultOld<TValue> Failed(string message, Exception? exception = null) =>
new(false, message, default, exception);
public static ResultOld<TValue> HandleResult(TValue? value, string failedMessage, Exception? exception = null)
{
return value == null ? Failed(failedMessage, exception) : Ok(value);
}
}
public class ListResultOld<TItem> : ResultOld
{
public ListResultOld(bool success, string message, int totalCount, IEnumerable<TItem>? items, int limit = -1, int offset = -1, Exception? exception = null) : base(success, message, exception)
{
Items = items != null ? new List<TItem>(items) : new List<TItem>();
TotalCount = totalCount;
Limit = limit;
Offset = offset;
}
public ListResultOld(ResultOld bObj) : base(bObj)
{
Items = new List<TItem>();
}
public readonly IReadOnlyList<TItem> Items;
/// <summary>
/// The amount of items that this result contains.
/// </summary>
public int Count => Items.Count;
/// <summary>
/// The total amount of item that is available.
/// </summary>
public int TotalCount { get; }
/// <summary>
/// The limit this result contains
/// </summary>
public int Limit { get; }
/// <summary>
/// The offset this result has the items from.
/// </summary>
public int Offset { get; }
public static ListResultOld<TItem> Ok(IEnumerable<TItem> items, int totalCount = -1, int limit = -1, int offset = -1) =>
new(true, string.Empty, totalCount, items, limit, offset);
public new static ListResultOld<TItem> Failed(string message, Exception? exception = null) =>
new(false, message, -1, null, exception: exception);
}

View File

@ -1,5 +1,4 @@
using System.Security.Cryptography; using System.Security.Cryptography;
using DotBased.Monads;
namespace DotBased.Utilities; namespace DotBased.Utilities;
@ -8,12 +7,12 @@ public static class Cryptography
/* /*
* https://gist.github.com/therightstuff/aa65356e95f8d0aae888e9f61aa29414 * https://gist.github.com/therightstuff/aa65356e95f8d0aae888e9f61aa29414
*/ */
public static Result<string> ExportPublicKeyToPem(RSACryptoServiceProvider csp) public static ResultOld<string> ExportPublicKeyToPem(RSACryptoServiceProvider csp)
{ {
var outputStream = new StringWriter(); var outputStream = new StringWriter();
var parameters = csp.ExportParameters(false); var parameters = csp.ExportParameters(false);
if (parameters.Exponent == null || parameters.Modulus == null) if (parameters.Exponent == null || parameters.Modulus == null)
return ResultError.Fail("RSAParameters are empty!"); return ResultOld<string>.Failed("RSAParameters are empty!");
using (var stream = new MemoryStream()) using (var stream = new MemoryStream())
{ {
var writer = new BinaryWriter(stream); var writer = new BinaryWriter(stream);
@ -24,7 +23,7 @@ public static class Cryptography
innerWriter.Write((byte)0x30); // SEQUENCE innerWriter.Write((byte)0x30); // SEQUENCE
EncodeLength(innerWriter, 13); EncodeLength(innerWriter, 13);
innerWriter.Write((byte)0x06); // OBJECT IDENTIFIER innerWriter.Write((byte)0x06); // OBJECT IDENTIFIER
var rsaEncryptionOid = new byte[] { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01 }; byte[] rsaEncryptionOid = new byte[] { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01 };
EncodeLength(innerWriter, rsaEncryptionOid.Length); EncodeLength(innerWriter, rsaEncryptionOid.Length);
innerWriter.Write(rsaEncryptionOid); innerWriter.Write(rsaEncryptionOid);
innerWriter.Write((byte)0x05); // NULL innerWriter.Write((byte)0x05); // NULL
@ -45,20 +44,20 @@ public static class Cryptography
bitStringWriter.Write(paramsStream.GetBuffer(), 0, paramsLength); bitStringWriter.Write(paramsStream.GetBuffer(), 0, paramsLength);
} }
var bitStringLength = (int)bitStringStream.Length; int bitStringLength = (int)bitStringStream.Length;
EncodeLength(innerWriter, bitStringLength); EncodeLength(innerWriter, bitStringLength);
innerWriter.Write(bitStringStream.GetBuffer(), 0, bitStringLength); innerWriter.Write(bitStringStream.GetBuffer(), 0, bitStringLength);
} }
var length = (int)innerStream.Length; int length = (int)innerStream.Length;
EncodeLength(writer, length); EncodeLength(writer, length);
writer.Write(innerStream.GetBuffer(), 0, length); writer.Write(innerStream.GetBuffer(), 0, length);
} }
var base64 = Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length).ToCharArray(); char[] base64 = Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length).ToCharArray();
// WriteLine terminates with \r\n, we want only \n // WriteLine terminates with \r\n, we want only \n
outputStream.Write("-----BEGIN PUBLIC KEY-----\n"); outputStream.Write("-----BEGIN PUBLIC KEY-----\n");
for (var i = 0; i < base64.Length; i += 64) for (int i = 0; i < base64.Length; i += 64)
{ {
outputStream.Write(base64, i, Math.Min(64, base64.Length - i)); outputStream.Write(base64, i, Math.Min(64, base64.Length - i));
outputStream.Write("\n"); outputStream.Write("\n");
@ -67,7 +66,7 @@ public static class Cryptography
outputStream.Write("-----END PUBLIC KEY-----"); outputStream.Write("-----END PUBLIC KEY-----");
} }
return outputStream.ToString(); return ResultOld<string>.Ok(outputStream.ToString());
} }
private static void EncodeLength(BinaryWriter stream, int length) private static void EncodeLength(BinaryWriter stream, int length)
@ -83,15 +82,15 @@ public static class Cryptography
default: default:
{ {
// Long form // Long form
var temp = length; int temp = length;
var bytesRequired = 0; int bytesRequired = 0;
while (temp > 0) while (temp > 0)
{ {
temp >>= 8; temp >>= 8;
bytesRequired++; bytesRequired++;
} }
stream.Write((byte)(bytesRequired | 0x80)); stream.Write((byte)(bytesRequired | 0x80));
for (var i = bytesRequired - 1; i >= 0; i--) for (int i = bytesRequired - 1; i >= 0; i--)
{ {
stream.Write((byte)(length >> (8 * i) & 0xff)); stream.Write((byte)(length >> (8 * i) & 0xff));
} }
@ -103,7 +102,7 @@ public static class Cryptography
private static void EncodeIntegerBigEndian(BinaryWriter stream, byte[] value, bool forceUnsigned = true) private static void EncodeIntegerBigEndian(BinaryWriter stream, byte[] value, bool forceUnsigned = true)
{ {
stream.Write((byte)0x02); // INTEGER stream.Write((byte)0x02); // INTEGER
var prefixZeros = value.TakeWhile(t => t == 0).Count(); int prefixZeros = value.TakeWhile(t => t == 0).Count();
if (value.Length - prefixZeros == 0) if (value.Length - prefixZeros == 0)
{ {
EncodeLength(stream, 1); EncodeLength(stream, 1);
@ -121,7 +120,7 @@ public static class Cryptography
{ {
EncodeLength(stream, value.Length - prefixZeros); EncodeLength(stream, value.Length - prefixZeros);
} }
for (var i = prefixZeros; i < value.Length; i++) for (int i = prefixZeros; i < value.Length; i++)
{ {
stream.Write(value[i]); stream.Write(value[i]);
} }