Skip to content

Repository files navigation

QueryArgumentEncryptor

NuGet version (SoftCircuits.QueryArgumentEncryptor)

Install-Package SoftCircuits.QueryArgumentEncryptor

QueryArgumentEncryptor makes it easy to pass private data as a URL query argument.

When passing data as a query argument in a URL, sometimes that data contains sensitive information that you do not want to expose to the user. In addition, sometimes it is important to ensure that data is not tampered with. For example, if a query argument contained an ID associated with the current user, someone could edit the ID and potentially expose information for another user.

QueryArgumentEncryptor solves both issues by converting any number of key/value pairs into a single, encrypted string. The data is encrypted using AES-256-GCM, which provides both confidentiality and built-in tamper detection — if the encrypted string is modified in any way, or decrypted with the wrong password, decryption fails.

Using the Class

QueryArgumentEncryptor derives from Dictionary<string, string>. So you can add data to it using the Dictionary class' methods and properties.

ArgumentEncryptor args = new ArgumentEncryptor("Password123");
args.Add("Key1", "Value1");
args.Add("Key2", "Value2");

Next, use the EncryptData() method to encrypt everything into a single string. By default, the encrypted string will be URL encoded. You can set the urlEncode argument to override this.

string url = string.Format("http://www.mydomain.com?data={0}", encryptor.EncryptData());

The page receiving this URL request can then reconstitute the original data from the query argument. (Obviously, the password must match the one used to create the argument.)

string arg = /* Value of query argument */

// Note: An exception is thrown if the password or data is invalid.
ArgumentEncryptor args = new ArgumentEncryptor("Password123", arg);
// Get some data
string s = args["Key1"];

If you'd rather not have an exception thrown for invalid data, use TryDecryptData() instead:

ArgumentEncryptor args = new ArgumentEncryptor("Password123");
if (args.TryDecryptData(arg))
{
    // Data was valid
    string s = args["Key1"];
}

Version Compatibility

Starting with version 3.0, this library uses a new, stronger encryption format (AES-256-GCM in place of the previous algorithm). Encrypted strings produced by version 2.x cannot be decrypted by version 3.0 or later, and vice versa.

If your application has previously issued long-lived URLs containing encrypted query arguments (for example, links emailed to users or saved for later use), those links will stop working once you upgrade to version 3.0. Consider this before upgrading if such links may still be in use, and plan to regenerate or expire them as needed.

About

Class to encrypt any number of key/value pairs so that they can be passed as a single query argument.

Topics

Resources

Stars

2 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages