find and solve || findandsolve.com
Please wait.....

Encrypt and Decrypt String in ASP.NET Core-.NET 5

Encryption is the process of converting data into ciphertext so that any unauthorized individuals cannot access the data.In the article, i will use the Advanced Encryption Standard (AES) algorithm to encrypt and decrypt a string in C#.In the tutorial AesManaged class provides methods to encrypt and decrypt string data using the AES algorithm.In the code, I used a predefined Aes class which is in System.Security.Cryptography namespace that uses the same key for encryption and decryption.In the following code example,how to encrypt a string according to the AES algorithm with the Cryptography function in C#.

        private static string key = "b14ca5898a4e4142aace2ea2143a2410";
        public static string EncryptString(string plainText)
        {
            byte[] iv = new byte[16];
            byte[] array;
            using (Aes aes = Aes.Create())
            {
                aes.Key = Encoding.UTF8.GetBytes(key);
                aes.IV = iv;
                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream))
                        {
                            streamWriter.Write(plainText);
                        }
                        array = memoryStream.ToArray();
                    }
                }
            }
            return Convert.ToBase64String(array);
        }

      public static string EncryptNumber(string encryptString)
        {
            string EncryptionKey = "0123456789ABCWBDCAFDTRGBDSCXSTUVWXYZ";
            byte[] clearBytes = Encoding.Unicode.GetBytes(encryptString);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] {
            0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76
        });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    encryptString = Convert.ToBase64String(ms.ToArray());
                }             }
            return encryptString;
        }

In the given above example  that I used initialization vector (IV) which is of 16 bytes in size, the block size of the algorithm. IV is optional.

Decrypt a String With the Aes in C#

Decryption is the process of converting ciphertext back to the original data so that authorized individuals can access the data.The CreateDecryptor() function can decrypt data using a key.Now I am going to create new function for decrypt string using unique key like as given below.

       public static string DecryptString(string cipherText)
        {
            byte[] iv = new byte[16];
            byte[] buffer = Convert.FromBase64String(cipherText);
            using (Aes aes = Aes.Create())
            {
                aes.Key = Encoding.UTF8.GetBytes(key);//I have already defined "Key" in the above EncryptString function
                aes.IV = iv;
                ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
                using (MemoryStream memoryStream = new MemoryStream(buffer))
                {
                    using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Read))                     {
                        using (StreamReader streamReader = new StreamReader((Stream)cryptoStream))                         {
                          return streamReader.ReadToEnd();
                        }
                    }
                }
            }
        }

       public static string DecryptNumber(string cipherText)
        {
            string EncryptionKey = "0123456789ABCWBDCAFDTRGBDSCXSTUVWXYZ";
            cipherText = cipherText.Replace(" ", "+");
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] {
          0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76
        });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }
                    cipherText = Encoding.Unicode.GetString(ms.ToArray());
                }
            }
            return cipherText;
        }

In above article, I learned how to use a symmetric key for encryption and decryption using C#. As per our requirement, I can also use different types of methods present inside the Aes Class.There are two type of encryption and decryption example using Aes class.

If you have any question or suggestions, please mention them in the comments section.

Mahira  khanna

Mahira khanna

I have the skills you need for you company blog, website, or other content materials

Comments



Report Response