Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

How to: Use Data Protection 

The .NET Framework provides access to the data protection API (DPAPI), which allows you to encrypt data using information from the current user account or computer. When you use the DPAPI, you alleviate the difficult problem of explicitly generating and storing a cryptographic key.

Use the ProtectedMemory class to encrypt an array of in-memory bytes. This functionality is available in Microsoft Windows XP and later operating systems. You can specify that memory encrypted by the current process can be decrypted by the current process only, by all processes, or from the same user context. See the MemoryProtectionScope enumeration for a detailed description of ProtectedMemory options.

Use the ProtectedData class to encrypt a copy of an array of bytes. This functionality is available in Microsoft Windows 2000 and later operating systems. You can specify that data encrypted by the current user account can be decrypted only by the same user account, or you can specify that data encrypted by the current user account can be decrypted by any account on the computer. See the DataProtectionScope enumeration for a detailed description of ProtectedData options.

To encrypt in-memory data using data protection

  • Call the static Protect method while passing an array of bytes to encrypt, the entropy, and the memory protection scope.

To decrypt in-memory data using data protection

  • Call the static Unprotect method while passing an array of bytes to decrypt and the memory protection scope.

To encrypt data to a file or stream using data protection

  1. Create random entropy.

  2. Call the static Protect method while passing an array of bytes to encrypt, the entropy, and the data protection scope.

  3. Write the encrypted data to a file or stream.

To decrypt data from a file or stream using data protection

  1. Read the encrypted data from a file or stream.

  2. Call the static Unprotect method while passing an array of bytes to decrypt and the data protection scope.

Example

The following code example demonstrates two forms of encryption and decryption. First, the code example encrypts and then decrypts an in-memory array of bytes. Next, the code example encrypts a copy of a byte array, saves it to a file, loads the data back from the file, and then decrypts the data. The example displays the original data, the encrypted data, and the decrypted data.

No code example is currently available or this language may not be supported.

Compiling the Code

See Also

Community Additions

ADD
Show:
© 2015 Microsoft