Encrypting Data Using a Symmetric Provider
Retired Content |
---|
This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist. |
The latest Enterprise Library information can be found at the Enterprise Library site. |
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 static EncryptSymmetric method of the Cryptographer class, specifying the name of the symmetric provider to use and the data to encrypt as a string or a byte array.
QuickStart
For an extended example of how to use the EncryptSymmetric method to encrypt data, see Walkthrough: Encrypting a Secret.
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 base64-encoded.
string encryptedContentsBase64 = Cryptographer.EncryptSymmetric("symmProvider", "password");
'Usage
Dim encryptedContentsBase64 As String = Cryptographer.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 = Cryptographer.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() = Cryptographer.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.