Share via


Encrypting Data Using a Symmetric Provider

A common cryptography task is to encrypt data using a symmetric provider. You may want to do this when an application has data you want to keep secure.

Typical Goals

In this scenario, you want to use a symmetric provider to encrypt data that you provide. The output of the symmetric provider is encrypted data.

Solution

Call the appropriate overload of the EncryptSymmetric method of the CryptographyManager class, specifying the name of the symmetric provider to use and the data to encrypt as a string or a byte array.

Using EncryptSymmetric

The following code shows how to use the EncryptSymmetric method to encrypt data in the form of a string. The string returned by this overload is base-64 encoded. These examples assume you have obtained an instance of the CryptographyManager class through the Enterprise Library container and saved it in the variable named crypto.

string encryptedContentsBase64 = crypto.EncryptSymmetric("symmProvider", "password"); 
'Usage
Dim encryptedContentsBase64 As String = crypto.EncryptSymmetric("symmProvider", "password")

The following code shows how to use the EncryptSymmetric method to encrypt data in a byte array. This overload returns a byte array.

byte[] valueToEncrypt = Encoding.Unicode.GetBytes("password");
byte[] encryptedContents = crypto.EncryptSymmetric("symmProvider", valueToEncrypt);

// Clear the byte array memory that holds the password.
Array.Clear(valueToEncrypt, 0, valueToEncrypt.Length);
'Usage
Dim valueToEncrypt = Encoding.Unicode.GetBytes("password")
Dim encryptedContents As Byte() = crypto.EncryptSymmetric("symmProvider", valueToEncrypt)

' Clear the byte array memory that holds the password.
Array.Clear(valueToEncrypt, 0, valueToEncrypt.Length)

Usage Notes

Consider the following points when you are encrypting data:

  • Make sure you configure the appropriate symmetric provider in the Enterprise Library configuration tools.
  • Sensitive data should be cleared in memory as soon as possible. Leaving sensitive data unencrypted in memory can expose the data to security risks. You should note that data in memory may also end up on the hard disk, because the operating system can write data to a swap file. Also, if the computer crashes, the operating system can dump the contents of memory to disk.