Skip to main content

Encrypting and Decrypting Query Strings using AES Algorithm in C#



Introduction:

In modern web applications, it is often necessary to transmit sensitive data through URLs without compromising security. One common approach to achieve this is by encrypting the query strings before sending them and decrypting them on the receiving end. In this blog post, we will explore how to implement query string encryption and decryption using the AES (Advanced Encryption Standard) algorithm in C#.

Prerequisites:

Before proceeding with the implementation, make sure you have a basic understanding of C# and .NET development. Also, ensure you have the required cryptographic libraries.

Step 1: Setting up the AES Encryption and Decryption Methods

We will use the AES algorithm, a symmetric encryption algorithm, to encrypt and decrypt the query strings. Below are the methods to perform the encryption and decryption:

public static string EncryptString(string plainText)

    {

           // return plainText;

            using (Aes aesAlg = Aes.Create())

            {

                aesAlg.Key = Encoding.UTF8.GetBytes(Encryptkey);

                aesAlg.Mode = CipherMode.CBC;

 

                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

 

                using (MemoryStream msEncrypt = new MemoryStream())

                {

                    msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);

                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))

                    {

                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))

                        {

                            swEncrypt.Write(plainText);

                        }

                    }

 

                    byte[] encryptedBytes = msEncrypt.ToArray();

                    return Base64UrlEncoder.Encode(encryptedBytes);

                }

            }

        }

        public static string DecryptString(string cipherText)

        {

            //return cipherText;

            byte[] cipherBytes = Base64UrlEncoder.DecodeBytes(cipherText);

 

            //byte[] cipherBytes = Base64UrlEncoderDecoder.Base64UrlDecode(cipherText);

 

            using (Aes aesAlg = Aes.Create())

            {

                aesAlg.Key = Encoding.UTF8.GetBytes(Encryptkey);

                aesAlg.Mode = CipherMode.CBC;

                byte[] iv = new byte[aesAlg.IV.Length];

                Array.Copy(cipherBytes, 0, iv, 0, iv.Length);

                aesAlg.IV = iv;

 

                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

 

                using (MemoryStream msDecrypt = new MemoryStream(cipherBytes, iv.Length, cipherBytes.Length - iv.Length))

                {

                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))

                    {

                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                        {

                            return srDecrypt.ReadToEnd();

                        }

                    }

                }

            }

        }

Step 2: Encrypting the Query String

To encrypt the query string, you can call the EncryptString method from the QueryStringEncryption class.

string originalQueryString = "username=example_user&id=12345";

string encryptedQueryString =ueryStringEncryption.EncryptString(originalQueryString);

Step 3: Decrypting the Query String

To decrypt the encrypted query string, you can call the DecryptString method from the QueryStringEncryption class.

string encryptedQueryString = "FfTmCh50KRsXVtH5M4GTh5UQcT55PKRcZklSsg..";

string decryptedQueryString = QueryStringEncryption.DecryptString(encryptedQueryString);

Conclusion:

In this blog post, we have learned how to implement query string encryption and decryption using the AES algorithm in C#. By encrypting sensitive data in query strings, we can ensure secure transmission and protect sensitive information from unauthorized access. Remember to keep your encryption key secure and change it periodically for added security.

Please note that the above blog is a basic implementation for educational purposes. In a real-world scenario, you should consider additional security measures, such as using HTTPS for transmitting encrypted data and handling encryption keys securely. Also, ensure that you follow best practices for key management and encryption to ensure the overall security of your application.


 #AES encryption C Sharp #Query string security #Secure query parameter handling #C# encryption tutorial #AES algorithm example #Encrypt URL parameters #Data protection in query strings #Cryptography in C Sharp  #AES decryption with C Sharp #Query string encryption best practices #Secure data transmission  #Encrypt and decrypt URL parameters #C Sharp AES encryption guide #Query string data privacy #Data security in URL parameters

Popular posts from this blog

Get Documents Signed Using Adobe Sign API in C#

Electronic signatures have revolutionized the way businesses handle document workflows. Instead of dealing with cumbersome paper-based processes, electronic signatures offer a streamlined and efficient way to obtain legally binding signatures. Adobe Sign API takes this concept to the next level by providing developers with the tools to seamlessly integrate electronic signature capabilities into their applications. In this blog post, we will explore how to use the Adobe Sign API to send documents for signature via email using C#   Understanding Electronic Signatures and Adobe Sign API Electronic signatures, also known as e-signatures, are digital representations of a person's intent to agree to the content of a document. They hold the same legal weight as traditional ink signatures but offer the advantage of speed and convenience. Adobe Sign API allows developers to programmatically incorporate e-signatures into their applications, automating the signature process and enhancing the ...

Test Azure AD secured API with Postman

API deployed on Azure and secured by Azure AD. For example, we will create a simple Azure Function that returns weather data.  public static async Task Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); try { HttpResponseMessage response; AuthenticationContext authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/xxxxxxxxx"); ClientCredential clientCredential = new ClientCredential("xxxxx-xxxxx", "xxxxxx"); AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync("xxxx-xxxxx-xxxxx", clientCredential).Result; using (var httpClient = new HttpClient()) ...

Working with RabbitMQ using C#

RabbitMQ Topology A Queue  that works on the basis of FIFO (first in first out).  A Publisher is the component that generates some data that is pushed to the queue.  Installation Install the correct version of Erlang based on the operating system you are using. Download and install RabbitMQ server . Now  install the RabbitMQ .Net client from NuGet Package Manager. Sample Codes using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Text; using System.Threading; namespace PracticeRabbitMQ {     class Program     {         static void Main()         {             SendMessage("MessageID", "{MessageID: 1, MessageBody: 'Sample Message' }");             ReceiveMessage("MessageID");             Console.ReadLine();         }   ...