encrypt decrypt string in asp.net Core

March 22, 2019 0 comments
This article is all about Implementing Simple AES encryption decryption algorithm in Asp.net Core.

We can actually use the same code for .net framework 4.7.2 also.

Use using System.Security.Cryptography;
Just make sure the key which we use for encryption and decryption is same. In our case we are using following key (This key I have copied from some references I already have.)



private static string keyString = "E546C8DF278CD5931069B522E695D4F2";



For encryption use following function, I generally keep Helper functions as static function

public static string EncryptString(string text)
        {
            var key = Encoding.UTF8.GetBytes(keyString);

            using (var aesAlg = Aes.Create())
            {
                using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))
                {
                    using (var msEncrypt = new MemoryStream())
                    {
                        using (var csEncrypt = new CryptoStream(msEncrypt, 
encryptor, CryptoStreamMode.Write))
                        using (var swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(text);
                        }

      var iv = aesAlg.IV;
      var decryptedContent = msEncrypt.ToArray();
      var result = new byte[iv.Length + decryptedContent.Length];
      Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
      Buffer.BlockCopy(decryptedContent, 0, result, iv.Length,
     decryptedContent.Length);

                        return Convert.ToBase64String(result);
                    }
                }
            }
        }

For decryption use following function


public static string DecryptString(string cipherText)
        {
            var fullCipher = Convert.FromBase64String(cipherText);

            var iv = new byte[16];
            var cipher = new byte[16];

            Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
            Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, iv.Length);
            var key = Encoding.UTF8.GetBytes(keyString);

            using (var aesAlg = Aes.Create())
            {
                using (var decryptor = aesAlg.CreateDecryptor(key, iv))
                {
                    string result;
                    using (var msDecrypt = new MemoryStream(cipher))
                    {
                        using (var csDecrypt = new CryptoStream(msDecrypt,
 decryptor, CryptoStreamMode.Read))
                        {
                            using (var srDecrypt = new StreamReader(csDecrypt))
                            {
                                result = srDecrypt.ReadToEnd();
                            }
                        }
                    }

                    return result;
                }
            }
        }

Share Share Tweet Share

0 thoughts on "encrypt decrypt string in asp.net Core"

LEAVE A REPLY