Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, March 21, 2024

Create an ECDSA signature with C# that can be verified using OpenSSL

 .net framework includes a handy library that can be used for generating digital signatures. However, the default output format is not DER and it cannot be verified using OpenSSL. There are many solutions in the Internet but they are super complex. The real solution is really simple, literaly half line of additional code. So here is some C# code that outputs DER encoded ECDSA signature that can be verified using OpenSSL:



  //assume data is a byte array that includes the data to be signed
  var ecdsa = ECDsa.Create(); // generates asymmetric key pair
  byte[] signature = ecdsa.SignData(data, HashAlgorithmName.SHA256, 
				DSASignatureFormat.Rfc3279DerSequence);

The last parameted of SignData does all the job :) You can find the official documentation of this method overload here. 

Tuesday, March 28, 2023

A simple role-based access control system for .NET

In many cases, I need a simple solution for adding authentication and authorization in my .NET project, so as to easily develop the rest of the system. I need something simple, e.g., hardcode some user information in the configuration file. ASP.NET Identity is for most of the times an overkill. So I decided to create my own solution. You can find the source code of my solution in this GitHub repository. 

The most important part is in the appsettings.Development.json file where users, their passwords, and their roles are defined. For example:


  "AuthorizedUsers": {
    "administrator": {
      "Password": "admin!",
      "Roles": [ "Administrator" ]
    },
    "user1": {
      "Password": "user1!",
      "Roles": [ "User" ]
    }
  }

Then, in the Program.cs file the following code must be added:


builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = "/Account/Login";

    });

builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
});
...
app.UseAuthentication();
app.UseAuthorization();

User authentication is handled by the Account controller. By default all pages are accessed only by authenticated users. If you want to restrict a page to particular role a decorator can be added to the corresponding controller method, e.g.:


[Authorize(Roles = "Administrator")]
public IActionResult Admin()
{
   return View();
}

I hope you can find this code useful

Monday, August 10, 2020

Create a JWT singed with RSA private key in .net core

The following example is a snippet of a C# code that generates an RSA private key out of a .pem file and uses it to sign a JWT. The privateKey variable, stores the contents of the .pem file minus the "-----BEGIN RSA PRIVATE KEY----" and "-----END RSA PRIVATE KEY-----" lines.

 
string privateKey = @"
MIIEpAIBAA
  ...
y53DdfYA==";
byte[] RSAprivateKey = Convert.FromBase64String(privateKey);
RSA rsa = RSA.Create();
rsa.ImportRSAPrivateKey(RSAprivateKey, out _);
var jwt = tokenHandler.CreateEncodedJwt(
   issuer: "...",
   audience: ...,
   ...
   signingCredentials: new SigningCredentials(
     key: new RsaSecurityKey(rsa),
     algorithm: SecurityAlgorithms.RsaSha256)
);

Monday, October 20, 2014

Handling C#, MVC entity validation errors in a meaningful way

MVC's entity framework is a convenient tool for abstracting databases. However, when something goes wrong the debug messages are not very meaningful. Especially when an entity validation exception occurs.

The following try, catch block catches an entity validation exception and concatenates all validation error messages into a single string. Then this string can be displayed in a debug message.


try
{
   entities.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
   var errorMessages = ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage);
   //Join the list to a single string. 
   var fullErrorMessage = string.Join("; ", errorMessages);
   throw new Exception(fullErrorMessage);
}

Sunday, April 1, 2012

Fast file searching in C#

This code shows how can you search for a file in C# using windows index and OleDB. The code below is tested in windows Vista where file indexing is enable by default. The following function, when called, outpust the fullpath of the file in request. It uses the operating system's file index therefore is very fast!


using System;
using System.Data.OleDb;

namespace MyBrowser
{
    class Browser
    {
        public void findFile(string fileName)
        {
            
            try
            {
                string url = "provider=Search.CollatorDSO.1;" +
                    "EXTENDED PROPERTIES=\"Application=Windows\"";
                OleDbConnection connection = new OleDbConnection(url);
                string queryString = "Select System.ItemPathDisplay from "+
                    "SystemIndex where System.FileName ='" + fileName + "' ";
                Console.WriteLine(queryString);
                OleDbCommand command = new OleDbCommand(queryString, connection);
                connection.Open();
                OleDbDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine(reader[0].ToString());
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            
        }
    }
}