Encrypt Decrypt Data with Sqids in .NET Core

Introduction

A simple library called Sqids, or "squids," lets you encode numbers like 117 into strings like jc7, which you can then decode back into the original numbers. Sqids is a helpful tool for obscuring numbers, such as consecutive numeric IDs, so they appear random and can be used in URLs and other contexts.

Install the Sqids in .NET Core

Install-Package Sqids

Alternatively, using the .NET CLI:

dotnet add package Sqids

Alternatively, using the NuGet Package Manager:

Encrypt Decrypt Data with Sqids

Usage

Everywhere you need is an instance of the SqidsEncoder class, which is the main class responsible for both encoding and decoding of the data.

If you are using the default constructor of the SqidsEncoder, then it will initialize with the default options.

If you want to customize the options, then we need to provide the details; then it will use that data whenever we want to encode and decode the data.

If you're using.NET 7 or a greater version, then you need to specify the numeric type for the encoder most commonly int datatype.

var sqlids = new SqidsEncoder<int>();

Note: You can use any integral numeric type (e.g., long, byte, short, etc.) as the type of argument. Int is just the most common one, but if you need to encode or decode larger numbers, then you could use long or ulong instead.

If you're application targeting an older framework than .NET 7, SqidsEncoder only supports int and there is no generic type parameter you need to supply, so just:

var sqids = new SqidsEncoder();

Single Number Encode and Decode

var sqids = new SqidsEncoder<int>();
var rank = 117;
var encodedRank = sqids.Encode(rank);
var decodeRank = sqids.Decode(encodedRank).Single();

Console.WriteLine("Plain text value, {0} - {1}", nameof(rank), rank);
Console.WriteLine("\nEncoded value, {0} - {1}", nameof(encodedRank), encodedRank);
Console.WriteLine("\nDecoded value, {0} - {1}", nameof(decodeRank), decodeRank);

Encrypt Decrypt Data with Sqids

Multiple Numbers Encode and Decode

var sqids = new SqidsEncoder<int>();

var encodedRank = sqids.Encode(117, 234, 717);
var decodeRank = sqids.Decode(encodedRank);

Console.WriteLine("Encoded value, {0} - {1}", nameof(encodedRank), encodedRank);
foreach (var rank in decodeRank)
{
    Console.WriteLine("Decoded value, {0} - {1}", nameof(rank), rank);
}

Encrypt Decrypt Data with Sqids

Customizations

By passing an instance of SqidsOptions to the constructor of SqidsEncoder, you can easily customize the blocklist (the words that should not appear in the IDs), the minimum length of the IDs (how long the IDs should be at minimum), and the alphabet (the characters that Sqids uses to encode the numbers).

All the properties are configurable; those that you omit will revert to their initial settings.

Custom Alphabet

You can provide Sqids with your own unique alphabet to use in the IDs, preferably shuffled:

var sqids = new SqidsEncoder<int>(new()
{
    // This is a shuffled version of the default alphabet,
    // which includes lowercase letters (a-z), uppercase letters (A-Z), and digits (0-9)
    Alphabet = "mTHivO7hx3RAbr1f586SwjNnK2lgpcUVuG09BCtekZdJ4DYFPaWoMLQEsXIqyz",
});

Minimum Length

Sqids, by default, encodes a given integer using the fewest characters feasible. However, you can set this using the MinLength option if you want all of your IDs to be at least a specific length (for example, for aesthetic purposes):

var sqids = new SqidsEncoder<int>(new()
{
    MinLength = 7,
});

Custom Blocklist

With the extensive default blocklist that Sqids provides, you can be sure that no frequent cruse terms or other offensive words will ever appear in your IDs. The following additional things can be added to this default blocklist:

var sqids = new SqidsEncoder<int>(new()
{
    BlockList = { "select", "int", "you", "else" },
});
var sqids = new SqidsEncoder<int>(new()
{
    MinLength = 7,
    Alphabet = "mTHivO7hx3RAbr1f586SwjNnK2lgpcUVuG09BCtekZdJ4DYFPaWoMLQEsXIqyz",
    BlockList = { "select", "int", "you", "else" }
});

var encodedRank = sqids.Encode(117);
var decodeRank = sqids.Decode(encodedRank);

Console.WriteLine("Encoded value, {0} - {1}", nameof(encodedRank), encodedRank);
foreach (var rank in decodeRank)
{
    Console.WriteLine("Decoded value, {0} - {1}", nameof(rank), rank);
}

Encrypt Decrypt Data with Sqids

Advanced Usage
 

Decoding single number

When decoding input from the user, you can utilize C#'s pattern matching functionality to extract the number in one go and execute the appropriate check:

if (sqids.Decode(rank) is [var number])
{
    // you can now use 'number' (which is an 'int') however you wish
}

Take note When the input is invalid, Decode produces an empty array; this expression makes sure that the decoded result is exactly one integer and not more than one.

Dependency injection

SqidsEncoder only needs to be registered as a singleton service in order to be used with a dependency injection system:

With default options

services.AddSingleton<SqidsEncoder<int>>();

With custom options

services.AddSingleton(new SqidsEncoder<int>(new()
{
    Alphabet = "SwjNnK2lgpcUVuG09BCtekZdJ4DYFPaWoMLQEsXIqyz",
    MinLength = 7,
}));

And then you can inject it anywhere you need it in your application.

public class ValuesController
{
    private readonly SqidsEncoder<int> _sqids;

    public ValuesController(SqidsEncoder<int> sqids)
    {
        _sqids = sqids;
    }
}
public class EmployeeService : IEmployeeService
{
    private readonly SqidsEncoder<int> _sqids;

    public ValuesController(SqidsEncoder<int> sqids)
    {
        _sqids = sqids;
    }
}

We learned the new technique and evolved together.

Happy coding! 😊


Similar Articles