asp. net core 4 Common Data Encryption Algorithms

  • 2021-11-13 07:11:14
  • OfStack

0. Preface

In this article, we will introduce the encryption and decryption of net core. In an Web application, the user's password is stored as password data using the MD5 value. In other cases, encryption and decryption functions will also be used.

Common encryption algorithms are divided into symmetric encryption and asymmetric encryption. The so-called symmetric encryption means that the encryption key and decryption key are the same as 1, while asymmetric encryption means that the value of encryption key and decryption ecstasy are different. However, MD5, which we often use in the process of saving user login password, is not an encryption algorithm in essence, but an information summary algorithm. However, MD5 as far as possible to ensure that the last calculated value of each string is not 1, so MD5 is commonly used as a confidential value in password preservation.

1. Common symmetric encryption algorithms

Symmetric encryption algorithm, simply speaking, encryption and decryption use the same key for operation. For most encryption algorithms, decryption and encryption are an inverse operation. The security of symmetric encryption algorithm depends on the length of key, and the longer the key, the safer it is. Of course, using overly long keys is not recommended.

So, let's take a look at the common symmetric encryption algorithms and how C # can be implemented.

1.1 DES and DESede algorithms

DES algorithm and DESede algorithm (also called triple DES algorithm) are collectively called DES series algorithms. DES is called Data Encryption Standard, that is, data encryption standard, which is a block algorithm using key encryption. DESede is to encrypt DES for the same block of data three times. I won't introduce the principle too much here. Let's take a look at how to realize DES encryption/decryption in net core.

In the Utils project, create a directory Security :

Under the Security directory, create the DESHelper class:


namespace Utils.Security
{
  public class DesHelper
  {
    
  }
}

Encryption and decryption implementation:


using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Utils.Security
{
  public static class DesHelper
  {
    static DesHelper()
    {
      DesHandler = DES.Create("DES");
      DesHandler.Key = Convert.FromBase64String("L1yzjGB2sI4=");
      DesHandler.IV = Convert.FromBase64String("uEcGI4JSAuY=");
    }

    private static DES DesHandler { get; }

    /// <summary>
    ///  Encrypted character 
    /// </summary>
    /// <param name="source"></param>
    /// <returns></returns>
    public static string Encrypt(string source)
    {
      try
      {
        using (var memStream = new MemoryStream())
        using (var cryptStream = new CryptoStream(memStream, DesHandler.CreateEncryptor(DesHandler.Key, DesHandler.IV),
          CryptoStreamMode.Write))
        {
          var bytes = Encoding.UTF8.GetBytes(source);
          cryptStream.Write(bytes, 0, bytes.Length);
          cryptStream.FlushFinalBlock();
          
          return Convert.ToBase64String(memStream.ToArray());
        }
      }
      catch (Exception e)
      {
        Console.WriteLine(e);
        return null;
      }
    }

    /// <summary>
    ///  Decryption 
    /// </summary>
    /// <param name="source"></param>
    /// <returns></returns>
    public static string Decrypt(string source)
    {
      try
      {
        using (var mStream = new MemoryStream(Convert.FromBase64String(source)))
        using (var cryptoStream =
          new CryptoStream(mStream, DesHandler.CreateDecryptor(DesHandler.Key, DesHandler.IV), CryptoStreamMode.Read))
        using (var reader = new StreamReader(cryptoStream))
        {
          return reader.ReadToEnd();
        }
      }
      catch (Exception e)
      {
        Console.WriteLine(e);
        return null;
      }
    }
  }
}

Each call DesHandler = DES.Create("DES"); One instance of DES algorithm implementation will be retrieved, so that the values of Key and IV attributes in each retrieved instance will also change. If you use it directly, the encrypted data will not be decrypted next time. In order to reduce this situation, the two attributes Key and IV are manually assigned to the code.

1.2 AES Encryption Algorithm

AES algorithm (Advanced Encryption Standard) is also the Advanced Data Encryption Standard algorithm, which is proposed to solve the loopholes in DES algorithm. The core of current AES algorithm is Rijndael algorithm. Of course, don't care too much about this. Let's look directly at how it is achieved:

Similarly, create an AesHelper class in the Security directory:


namespace Utils.Security
{
  public static class AesHelper
  {
    
  }
}

Specific encryption and decryption implementation:


using System;
using System.IO;
using System.Security.Cryptography;

namespace Utils.Security
{
  public static class AesHelper
  {
    static AesHelper()
    {
      AesHandler = Aes.Create();
      AesHandler.Key = Convert.FromBase64String("lB2BxrJdI4UUjK3KEZyQ0obuSgavB1SYJuAFq9oVw0Y=");
      AesHandler.IV = Convert.FromBase64String("6lra6ceX26Fazwj1R4PCOg==");
    }

    private static Aes AesHandler { get; }

    public static string Encrypt(string source)
    {
      using (var mem = new MemoryStream())
      using (var stream = new CryptoStream(mem, AesHandler.CreateEncryptor(AesHandler.Key, AesHandler.IV),
        CryptoStreamMode.Write))
      {
        using (var writer = new StreamWriter(stream))
        {
          writer.Write(source);
        }  
        return Convert.ToBase64String(mem.ToArray());
      }
      
    }

    public static string Decrypt(string source)
    {
      var data = Convert.FromBase64String(source);
      using (var mem = new MemoryStream(data))
      using (var crypto = new CryptoStream(mem, AesHandler.CreateDecryptor(AesHandler.Key, AesHandler.IV),
        CryptoStreamMode.Read))
      using (var reader = new StreamReader(crypto))
      {
        return reader.ReadToEnd();
      }
    }
  }
}

2. Common asymmetric encryption algorithms

Asymmetric encryption algorithm means that the encryption key and decryption key are not the same. The secret keys of asymmetric encryption algorithms usually appear in pairs, which are divided into public keys and private keys. The public key can be sent to the data interacting party in a public form without the risk of disclosure. Because of the asymmetric encryption algorithm, it is impossible to calculate the private key from the public key, and vice versa.

Generally, asymmetric encryption algorithm uses public key for encryption and private key for decryption.

2.1 RSA algorithm

RSA algorithm is a standard asymmetric encryption algorithm, and its name comes from the initials of three inventors' surnames. RSA public key cryptosystem is a cryptosystem that uses different encryption keys and decryption keys, and "it is computationally infeasible to deduce decryption keys from known encryption keys". Its security depends on the length of the key, and it is almost impossible to crack the 1024-bit key.

Similarly, create the RSAHelper class under Utils. Security:


namespace Utils.Security
{
  public static class RsaHelper
  {
    
  }
}

Concrete realization:


using System;
using System.Security.Cryptography;

namespace Utils.Security
{
  public static class RsaHelper
  {
    public static RSAParameters PublicKey { get; private set; }
    public static RSAParameters PrivateKey { get; private set; }

    static RsaHelper()
    {
      
    }

    public static void InitWindows()
    {
      var parameters = new CspParameters()
      {
        KeyContainerName = "RSAHELPER" //  Default RSA The name of the container where the key is stored 
      };
      var handle = new RSACryptoServiceProvider(parameters);
      PublicKey = handle.ExportParameters(false);
      PrivateKey = handle.ExportParameters(true);
    }

    public static void ExportKeyPair(string publicKeyXmlString, string privateKeyXmlString)
    {
      var handle = new RSACryptoServiceProvider();
      handle.FromXmlString(privateKeyXmlString);
      PrivateKey = handle.ExportParameters(true);
      handle.FromXmlString(publicKeyXmlString);
      PublicKey = handle.ExportParameters(false);
    }
    public static byte[] Encrypt(byte[] dataToEncrypt)
    {
      try
      {
        byte[] encryptedData;
        using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
        {
          RSA.ImportParameters(PublicKey);
          encryptedData = RSA.Encrypt(dataToEncrypt, true);
        }

        return encryptedData;
      }
      catch (CryptographicException e)
      {
        Console.WriteLine(e.Message);
        return null;
      }
    }

    public static byte[] Decrypt(byte[] dataToDecrypt)
    {
      try
      {
        byte[] decryptedData;
        using (var rsa = new RSACryptoServiceProvider())
        {
          rsa.ImportParameters(PrivateKey);
          decryptedData = rsa.Decrypt(dataToDecrypt, true);
        }
        return decryptedData;
      }
      catch (CryptographicException e)
      {
        Console.WriteLine(e.ToString());
        return null;
      }
    }
  }
}

Because of the particularity of RSA, it is necessary to set the public key and private key in advance. C # supports a variety of ways to import keys, so I won't go into that here.

3. Information summarization algorithm

This algorithm is not strictly an encryption algorithm, because it is completely irreversible. That is to say, after encrypting with this type of algorithm, the data cannot be decrypted and restored. Of course, it is precisely because this feature is often used to save passwords. Because this can avoid some people get the database and code, can simply reverse the user's password.

3.1 MD5 algorithm

The most commonly used information digest algorithms are MD5 encryption algorithm, MD5 information digest algorithm (English: MD5 Message-Digest Algorithm), and a widely used cryptographic hash function, which can generate a 128-bit (16-byte) hash value (hash value) to ensure the integrity of information transmission.

The principle is not explained. Let's see how to implement it. As usual, create MD5Helper under Security:


namespace Utils.Security
{
  public static class Md5Helper
  {
    
  }
}

Concrete realization:


using System.Security.Cryptography;
using System.Text;

namespace Utils.Security
{
  public static class Md5Helper
  {
    private static MD5 Hanlder { get; } = new MD5CryptoServiceProvider();

    public static string GetMd5Str(string source)
    {
      var data = Encoding.UTF8.GetBytes(source);
      var security = Hanlder.ComputeHash(data);
      var sb = new StringBuilder();
      foreach (var b in security)
      {
        sb.Append(b.ToString("X2"));
      }

      return sb.ToString();
    }
  }
}

4 Summary

This article briefly introduces the implementation of four commonly used encryption algorithms, of course, the most commonly used one is MD5, because this is the encryption algorithm used by most systems to save passwords.

The above is asp. net core Common 4 kinds of data encryption algorithm details, more information about asp. net core data encryption algorithm please pay attention to other related articles on this site!


Related articles: