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, April 4, 2023

Authenticate users in python scripts using their Google account


Google offers user authentication through OpenID Connect. Although usually, this feature is used by web sites, it can also be used with desktop applications. In this repository you can find a Python3 script that authenticates users based on their Google account. 

What this script does is, it opens a web browser that redirects user to Google's authorization page and at the same time it begins a web server that "listens" for the access code. Upon receiving the access code it "exchanges" for an id token that includes user information.

Since the client secret of a desktop application can be easily protected, this script leverages Proof Key for Code Exchange by OAuth Public Clients, a technology defined in RFC 7636 and supported by Google. With PKCE, the script generates a random code verifier and transmits its SHA-256 hash when requesting the access code. Then, it transmits the actual code verifier when requesting the id token. 

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

Wednesday, April 6, 2022

Make fun things with your home IoT devices, securely over the internet.

I am planning to start a series of posts discussing how to put your IoT devices in the internet and do fun stuff with them. I will provide them as GitHub Wiki pages and I will also provide code and scripts when this is possible. This page will act as a placeholder.

Interact using Alexa with your IoT devices

In this first post I am using the excellent, free, Cloudflare Tunnel and I make my Raspberry Pi accessible over the internet using a custom domain and HTTPS. Only with a few clicks and no cost (apart from the cost of the domain name).

Then I provide an Amazon Alexa Skill that can be used for interacting with your Raspberry Pi using your Alexa device! In this simple example, I am implementing a simple REST API which is invoked using voice commands.

Have fun!


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)
);

Thursday, April 9, 2020

Deploying smart contracts to ganache using python and web3

Ganache is a useful tool that emulates Ethereum blockchain in your local machine and it is very practical for testing smart contracts. Most tutorials explain how to deploy a smart contract in ganache using truffle, which is a development framework by the same company. But this is not necessary. Here, I explain how to write and compile a contract using Remix, and deploy it using python and web3.py.

Write your smart contract in remix and compile it. Then press the "ABI" button on the bottom left (see picture) and paste the output in a file. This will be our ABI_file. Do the same with the "Bytecode" bottom. This will be the bin_file. Then you can use the python script from this github repository. Make sure you have installed the dependencies and that you have modified the ABI_file and bin_file variables of the script accordingly.




Sunday, May 19, 2019

CoAP POST using libcoap

View a list of all libcoap examples here.

This example includes a CoAP server and a CoAP client. 
The client performs a CoAP POST request for the "coap://127.0.0.1/hello" resource. The server listens on port 5683 (default port) and prints the POSTed data

You can find the source code of this example, as well as, instructions for compiling it in Linux in this github repository, in the "post" folder.