Hashing, Encryption and Random in ASP.NET Core
Tags: dotnet, webdev, programming, tutorial
Published: 2023-06-21 10:05:06

In this blog, we will be going to discuss hashing, encryption, and random string generation in ASP.NET Core. We will examine a number of different approaches and explain why some common techniques should be avoided in the latest applications.

## What is ASP.NET Core?

ASP.NET Core is a free open-source platform that was developed by Microsoft along with .NET core. It is a cross-platform that supports almost every operating system like macOS, Windows, and Linux. ASP.NET Core is a great platform embedded with a lot of characteristics which helps build cloud-based application, device applications .NET Core can operate on Mac operating system also.

.NET Core has two major components. It adds a small runtime that is built from the same codebase as the .NET Framework CLR. The .NET Core runtime adds the same Garbage Collection and JIT (RyuJIT) but doesn’t add features like Application Domains or Code Access Security.

.NET Core also adds the base class libraries, this library is widely the same code as the .NET Framework class libraries, but have been factored (removal of dependencies) to enable us to ship a smaller set of libraries. These libraries are sent as System.* NuGet packages on NuGet.org.

## What is Hashing?
Hash functions can get input and return unique output creating a singular (sort of) “signature” for that input. Hashing was used in a number of ways: Finding duplicate/similar records as similar records/strings will produce a similar hash protected data as when the data is modified the calculated hash also replaced.

Hash tables to quickly locate records

Hashing is a common requirement for storing passwords over Databases but you need to be very careful when implementing security logic for yourself. Unless you have the best reason, you are far better off using a tried and tested library to handle this for you. If you do have a genuine requirement to hash a string yourself then you required to pay close attention to the algorithm you use.

#### Read More: [Asp.Net Core Improvements In .Net 5](https://www.ifourtechnolab.com/blog/asp-net-core-improvements-in-net-5)

You will repeatedly come over hashing examples similar to the following code:

```
{
  using (var algorithm = SHA512.Create()) //or MD5 SHA256 etc.
    {
      var hashedBytes = algorithm.ComputeHash(Encoding.UTF8.GetBytes(input));
                  
      return BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
    }
}

```

For a more secure we need to use another package including a NuGet reference to Microsoft.AspNetCore.Cryptography.Key derivation allows us to use PBKDF2 which is far harder to brute force.

This example uses the common secure technique of storing the data together with the hashed password:

```
public string CalcuHash(string input)
{
    var slt= GenerateSalt(2);
    var byt= KeyDerivation.Pbkdf2(input, salt, KeyDerivationPrf.HMACSHA512, 21, 16);

    return $"{ Convert.ToBase64String(slt) }:{ Convert.ToBase64String(byt) }";
}

```

Of course, the salt should be unique to each entry and not something that is guessable so we need the means to generate a random value. once again Random Number Generator was used rather than System’s random library.

## What is Encryption?
Encryption Functions provides a 1:1 mapping between an arbitrary length input and output and they are always reversible. The most important thing to note is that it's a reversible using method. And it's every time 1:1 for a given key. Now, they are multiple input: key pairs that might display the same output (in fact there usually are, depending on the encryption function). Good encrypted data is imperceptible from random noise.

.NET Core. encryption is fast and can encrypt or decrypt large amounts of Data, string, text, or files but requires a shared key. Asymmetric encryption can be used without shared a key, but can only encrypt or decrypt small texts depending on the key size.

Encrypting this method takes the three parameters and creates encrypted data that can only be decrypted using the same key and IV base64 strings. If encrypting large amounts of data, then a Crypto Stream should be used. See the example of Encrypt data in below code.

```
public string Encrypt(string txt, string IV, string key)
{
    Aes cipher = CreateCipher(key);
    cipher.IV = Convert.FromBase64String(IV);
 
    ICryptoTransform cryptTransform = cipher.CreateEncryptor();
    byte[] ptxt= Encoding.UTF8.GetBytes(txt);
    byte[] ciptxt= cryptTransform.TransformFinalBlock(ptxt, 0, ptxt.Length);
 
    return Convert.ToBase64String(ciptxt);
}

```

It is the common precondition to generate random strings. Not For only do they make outstanding primary keys (in many NoSQL data stores at least) but in addition, they are generally used for email validation and password reset process. Web and Mobile Developers often use a (modified) GUID for this:


Guid.NewGuid(). ToString("K")

That in returns a string similar like that: 84bc1c2db56140b39e35b040e6856457

This is often allowable but for a more random, more readable, and possibility shorter string we can come up with a better alternative:

```
public class RandomGen
{
    private const string AllowG= "abcdefghijklmnopqrstuvwxyz0123456789";

    public static string GenerateString(int LNG)
    {
        var bts= new byte[LNG];

        using (var rndm= RandomNumberGenerator.Create())
        {
            random.GetBytes(bts);
        }

        return new string(bytes.Select(x => AllowableCharacters[x % AllowG.Length]). ToArray());
    }
}

```

The key to this method is the use of the System.Security.Cryptography. random number generator. Create which returns a cryptographically strong random number generator by the random method. Random that class was returning the same pseudo-random numbers in the same order like random numbers given the same seed. The 'known' nature of the System. Random can be very useful in some difficult situations and security-related, the use of random number generator. Create is preferred.

#### Searching for Dedicated [ASP.Net Core Developer](https://www.ifourtechnolab.com/hire-asp-net-core-developer)? Your Search ends here.

The above example uses a base36 word but we can easily change that to your requirements. For example, if your end-users are expected to type in the string then you might want to remove characters that can be easily confused such as 0/o and 1/i.

If you want to create a random password that allows some specific characters also. The below example has a string of valid characters. The code uses this string to take one character at a time for the password and stops at the given length. In this example, we set the default length of the password as 12.

```
private static string CreateRandomPassword(int len= 12)  
{  
    
    string validc= "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*?_-";  
    Random random = new Random();  
  
 
    char[] chars = new char[len];  
    for (int j = 0; j < len; j++)  
    {  
        chars[j] = validc[random.Next(0, validc.len)];  
    }  
    return new string(chars);  
} 

```

## Conclusion
In this blog, we have discussed about hashing, encryption, and random string generation in ASP.NET Core with its benefits. We examined a number of different approaches and explained why some common techniques should be avoided in the latest applications. This method is very useful to manage the security of over site that can create strong random passwords for a new user.