Best way to encrypt/decrypt querystring in .Net

Please find the best way to do Encryption/Decryption in .net. If you use standard way of accessing query string parameter values after encrypting or hashing you will get errors. Using following way, it will generate safe Encryption/Decryption in query string.

Encrypt :

    static string Encrypt(string originalString)
    {
        if (String.IsNullOrEmpty(originalString))
        {
            return string.Empty;
        }
        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
        MemoryStream memoryStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memoryStream,
            cryptoProvider.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);
        StreamWriter writer = new StreamWriter(cryptoStream);
        writer.Write(originalString);
        writer.Flush();
        cryptoStream.FlushFinalBlock();
        writer.Flush();
        return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
    }

string qs = "?uid=" + Encrypt("sample user id & key");

Decrypt :

    static string Decrypt(string cryptedString)
    {
        if (String.IsNullOrEmpty(cryptedString))
        {
            return string.Empty;
        }
        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
        MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(cryptedString));
        CryptoStream cryptoStream = new CryptoStream(memoryStream,
            cryptoProvider.CreateDecryptor(bytes, bytes), CryptoStreamMode.Read);
        StreamReader reader = new StreamReader(cryptoStream);
        return reader.ReadToEnd();
    }

    private string GetRawUrlQueryString(string key)
    {
        string val = string.Empty;

        string url = HttpContext.Current.Request.RawUrl;

        int start = url.IndexOf("?");
        if (start >= 0)
        {
            string qs = url.Substring(start + 1);
            string[] parts = qs.Split('&');
            foreach (string part in parts)
            {
                if (part.Trim().StartsWith(key + "="))
                {
                    val = part.Trim().Replace(key + "=", "");
                    break;
                }
            }
        }
        return val;
    }

string receiveduid = GetRawUrlQueryString("uid");
string uid =  Decrypt(receivedui);

Important :

Do not use Request.QueryString["uid"] get the query string value as .net framework by default convert actual query string value with url encode. If so your decryption or base64 conversion will fail.

Comments

Popular posts from this blog

Embedding PowerBI with ASP.NET Core 2 and Angular(2,4,5)

Handling Exit Event of Console Application in C#

CSS text-overflow ellipsis in the beginning of the the text - Left Ellipsis using CSS in a Flex box