【 asp.net Core series] 12 data encryption algorithm

Time:2021-4-26

0. Preface

In this article, we will introduce the encryption and decryption of. Net core. In web applications, the user’s password is stored as password data using MD5 value. In other cases, encryption and decryption will also be used.

Common encryption algorithms are divided into symmetric encryption and asymmetric encryption. Symmetric encryption means that the encryption key and decryption key are the same, while asymmetric encryption means that the encryption key and decryption key are different. MD5, which is often used in the process of saving user login password, is not an encryption algorithm in essence, but an information digest algorithm. However, MD5 tries to ensure that the final calculated value of each string is different, so MD5 is often used as a secret value in password saving.

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 inverse operations. The security of symmetric encryption algorithm depends on the length of the key. The longer the key, the more secure it is. Of course, a key that is too long is not recommended.

So, let’s take a look at the common symmetric encryption algorithms and how to implement them.

1.1 DES and deSede algorithm

DES algorithm and deSede algorithm (also known as Triple DES algorithm) are collectively referred to as DES series algorithm. DES is fully known as data encryption standard, which is a block algorithm using key encryption. DeSede is to encrypt the same block of data three times. Here we don’t introduce the principle too much. Let’s see how to realize DES encryption / decryption in. Net core.

In the utils project, create a directorySecurity

In 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; }

        /// 
        ///Encrypted character
        /// 
        /// 
        /// 
        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;
            }
        }

        /// 
        ///Decryption
        /// 
        /// 
        /// 
        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;
            }
        }
    }
}

Every callDesHandler = DES.Create("DES");In this way, the values of key and IV in each 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 key and IV attributes are manually assigned in the code.

1.2 AES encryption algorithm

AES algorithm (Advanced Encryption Standard), also known as advanced data encryption standard algorithm, is an algorithm standard proposed to solve the loopholes in DES algorithm. The core of current AES algorithm is Rijndael algorithm. Of course, you don’t have to care too much about this. Let’s see how it works

Similarly, create an aeshelper class in the security Directory:

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

Specific implementation of encryption and decryption:

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 key and private key. The public key can be sent to the data exchange party in the form of public without the risk of leakage. Because of asymmetric encryption algorithm, private key cannot be calculated from public key, and vice versa.

Generally, asymmetric encryption algorithm uses public key to encrypt and private key to decrypt.

2.1 RSA algorithm

RSA algorithm is a standard asymmetric encryption algorithm. The first name comes from the surname of three inventors. RSA public key cryptosystem is a cryptosystem which uses different encryption key and decryption key. It is computationally infeasible to deduce decryption key from known encryption key. Its security depends on the length of the key, 1024 bit key is almost impossible to be cracked.

Again, in Utils.Security Create the rsahelper class under

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

Specific implementation:

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 // the default RSA container name for saving keys
            };
            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, public key and private key need to be set in advance. C # supports multiple ways to import keys, so I won’t introduce it too much here.

3. Information digest algorithm

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

3.1 MD5 algorithm

The most commonly used information digest algorithm is MD5 encryption algorithm. MD5 message digest algorithm (English: MD5 message digest algorithm), a widely used cryptographic hash function, can produce a 128 bit (16 byte) hash value to ensure the integrity and consistency 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
    {
        
    }
}

Specific implementation:

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 is MD5, because this is the encryption algorithm used by most systems to save passwords.

Please pay more attention to my blog “Mr. Gao’s cabin”

file

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]