1
0
mirror of https://github.com/XFox111/SimpleOTP.git synced 2026-04-22 08:00:45 +03:00
1
Implementing custom hashing algorithms
Eugene Fox edited this page 2024-09-18 16:56:42 +03:00

Important

This tutorial is made for educational purposes only! Do not use custom algorithms in public authenticator implementations!

Justification

This library is designed to be as flexible as possible to suit everyone's needs. This part is no exception, as it possibly can help to improve your service security.

In the current real-world scenarios it is unlikely that you ever need to implement custom algorithms.

Best practicies

Do

  • Do consider creating custom hashing algorithms only for internal business apps implementations
  • Do consider creating custom hashing algorithms only if you believe that will improve your corporate app's security

Don't

  • Do not ever implement custom algorithms for creating otpauth: URIs in public services.
  • Do not override default algorithm providers.

Creating new algorithms

The library utiliezes abstract KeyedHashAlgorithm class when managing different algorithms. If you need to implement a new one, or use one that is not included in the library by default (e.g. HMAC SHA-384), you can create a new class that inherits KeyedHashAlgorithm and override its methods.

Registering provider

The library has a mechanism that detects hashing algorithms based on OtpAlgorithm value. If you need to implement a new algorithm, you can register it using HashAlgorithmProviders.AddProvider method:

HashAlgorithmProviders.AddProvider<HMACSHA384>((OtpAlgorithm)"SHA384");

Once it has been registered it will be automatically recognized and used by the library.

Providers recognized by default and not required to be registered are:

Example

using SimpleOTP;
using SimpleOTP.Fluent;

HashAlgorithmProviders.AddProvider<HMACSHA384>((OtpAlgorithm)"SHA384");

string uri = "otpauth://totp/user@example.com?secret=KRUGKIDROVUWG2ZAMJZG653OEBTG66BO&algorithm=SHA384&issuer=example.com";

OtpConfig config = OtpConfig.Parse(uri);
Console.WriteLine(config.Algorithm); // SHA384
Console.WriteLine(config.ToUri()); // otpauth://totp/user@example.com?secret=KRUGKIDROVUWG2ZAMJZG653OEBTG66BO&algorithm=SHA384&issuer=example.com

Otp generator = OtpBuilder.FromConfig(config);
generator.Generate();	// Will use HMACSHA384 algorithm