If you have to use asymmetric encryption in your ASP.NET project you can use the class described in the article How to create asymmetric encryption utility class in ASP.NET in C#. To illustrate this you can create a page that permits you to generate a key and enter clear-text data through a text box. You can output the encrypted data through Convert.ToBase64String(). For decryption you should call Convert.FromBase64String() to get the encrypted bytes back and pass them into the DecryptData method:

 

private string KeyFileName;

protected void Page_Load(object sender, EventArgs e)

{

KeyFileName = Server.MapPath(“~/”) + “\\asymmetric_key.config”;

}

protected void GenerateKeyCommand_Click(object sender, EventArgs e)

{

try

{

PublicKeyText.Text = AsymmetricEncryptionUtility.GenerateKey(KeyFileName);

Response.Write(“Key generated successfully!<br/>”);

}

catch

{

Response.Write(“Exception occured when encrypting key!”);

}

}

 

protected void EncryptCommand_Click(object sender, EventArgs e)

{

// Check for encryption key

if (!File.Exists(KeyFileName))

{

Response.Write(“Missing encryption key. Please generate key!”);

}

 

try

{

byte[] data = AsymmetricEncryptionUtility.EncryptData(ClearDataText.Text, PublicKeyText.Text);

EncryptedDataText.Text = Convert.ToBase64String(data);

}

catch

{

Response.Write(“Unable to encrypt data!”);

}

}

 

protected void DecryptCommand_Click(object sender, EventArgs e)

{

// Check for encryption key

if (!File.Exists(KeyFileName))

{

Response.Write(“Missing encryption key. Please generate key!”);

}

 

try

{

byte[] data = Convert.FromBase64String(EncryptedDataText.Text);

ClearDataText.Text = AsymmetricEncryptionUtility.DecryptData(data, KeyFileName);

}

catch

{

Response.Write(“Unable to decrypt data!”);

}

}

The next picture shows the page:

 

The web page for asymmetric algorithms in C#

The web page for asymmetric algorithms in C#

Important note:

Probably your aspx page for asymmetric encryption will generates the next error message:

Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. To allow pages to override application request validation settings, set the requestValidationMode attribute in the httpRuntime configuration section to requestValidationMode=”2.0″. Example: <httpRuntime requestValidationMode=”2.0″ />. After setting this value, you can then disable request validation by setting validateRequest=”false” in the Page directive or in the <pages> configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case. For more information, see https://go.microsoft.com/fwlink/?LinkId=153133.

In this case you should follow the proposed settings.