Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 24 additions & 15 deletions docs/standard/security/how-to-use-data-protection.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
---
title: "How to: Use Data Protection"
title: "How to use data protection"
description: Learn how to use data protection by accessing the data protection API (DPAPI) in .NET.
ms.date: 07/14/2020
ms.date: 07/22/2026
ai-usage: ai-assisted
dev_langs:
- "csharp"
- "vb"
Expand All @@ -17,16 +18,16 @@ helpviewer_keywords:
- "data [.NET], encryption"
ms.assetid: 606698b0-cb1a-42ca-beeb-0bea34205d20
---
# How to: Use Data Protection
# How to use data protection

> [!NOTE]
> This article applies to Windows.
>
> For information about ASP.NET Core, see [ASP.NET Core Data Protection](/aspnet/core/security/data-protection/introduction).

.NET 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.
.NET provides access to the data protection API (DPAPI), which lets you encrypt data using information from the current user account or computer. When you use the DPAPI, you avoid the difficult problem of explicitly generating and storing a cryptographic key.

Use the <xref:System.Security.Cryptography.ProtectedData> class to encrypt a copy of an array of bytes. 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 <xref:System.Security.Cryptography.DataProtectionScope> enumeration for a detailed description of <xref:System.Security.Cryptography.ProtectedData> options.
Use the <xref:System.Security.Cryptography.ProtectedData> class to encrypt a copy of an array of bytes. You can specify that only the same user account can decrypt the data, or that any account on the computer can decrypt it. For a detailed description of <xref:System.Security.Cryptography.ProtectedData> options, see the <xref:System.Security.Cryptography.DataProtectionScope> enumeration.

## Encrypt data to a file or stream using data protection

Expand All @@ -44,24 +45,32 @@ Use the <xref:System.Security.Cryptography.ProtectedData> class to encrypt a cop

## 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.
The following code example shows two forms of encryption and decryption. First, the code encrypts and then decrypts an in-memory array of bytes. Next, the code 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.

[!code-csharp[DPAPI-HowTO#1](../../../samples/snippets/csharp/VS_Snippets_CLR/DPAPI-HowTO/cs/sample.cs#1)]
[!code-vb[DPAPI-HowTO#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/DPAPI-HowTO/vb/sample.vb#1)]
> [!IMPORTANT]
> <xref:System.Security.Cryptography.ProtectedMemory> is only available for .NET Framework. <xref:System.Security.Cryptography.ProtectedData> is available on .NET and .NET Framework.

## Compiling the Code
### [.NET](#tab/net)

This example compiles and runs only when targeting .NET Framework and running on Windows.
This sample compiles and runs when you target .NET on Windows. To compile the sample, add the [`System.Security.Cryptography.ProtectedData`](https://www.nuget.org/packages/System.Security.Cryptography.ProtectedData/) NuGet package.

- Include a reference to `System.Security.dll`.
:::code language="csharp" source="./snippets/how-to-use-data-protection/net/csharp/sample.cs":::
:::code language="vb" source="./snippets/how-to-use-data-protection/net/vb/sample.vb":::

- Include the <xref:System>, <xref:System.IO>, <xref:System.Security.Cryptography>, and <xref:System.Text> namespace.
### [.NET Framework](#tab/net-framework)

This sample compiles and runs when you target .NET Framework on Windows. To compile the sample, add reference to the `System.Security.dll` library.

:::code language="csharp" source="./snippets/how-to-use-data-protection/framework/csharp/sample.cs":::
:::code language="vb" source="./snippets/how-to-use-data-protection/framework/vb/sample.vb":::

---

## See also

- [Cryptography Model](cryptography-model.md)
- [Cryptographic Services](cryptographic-services.md)
- [Cross-Platform Cryptography](cross-platform-cryptography.md)
- [Cryptography model](cryptography-model.md)
- [Cryptographic services](cryptographic-services.md)
- [Cross-platform cryptography](cross-platform-cryptography.md)
- <xref:System.Security.Cryptography.ProtectedMemory>
- <xref:System.Security.Cryptography.ProtectedData>
- [ASP.NET Core Data Protection](/aspnet/core/security/data-protection/introduction)
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{9B14A2C4-4E4E-4A8E-9C3B-8F5F8D9C6A21}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>DataProtectionSample</RootNamespace>
<AssemblyName>DataProtectionSample</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Security" />
</ItemGroup>
<ItemGroup>
<Compile Include="sample.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
// <snippet1>
using System;
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

public class MemoryProtectionSample
{
public static void Main() => Run();

public static void Run()
public static void Main()
{
try
{
Expand All @@ -19,21 +16,21 @@ public static void Run()
///////////////////////////////

// Create the original data to be encrypted (The data length should be a multiple of 16).
byte[] toEncrypt = UnicodeEncoding.ASCII.GetBytes("ThisIsSomeData16");
byte[] toEncrypt = Encoding.ASCII.GetBytes("ThisIsSomeData16");

Console.WriteLine($"Original data: {UnicodeEncoding.ASCII.GetString(toEncrypt)}");
Console.WriteLine(value: $"Original data: {Encoding.ASCII.GetString(toEncrypt)}");
Console.WriteLine("Encrypting...");

// Encrypt the data in memory.
EncryptInMemoryData(toEncrypt, MemoryProtectionScope.SameLogon);

Console.WriteLine($"Encrypted data: {UnicodeEncoding.ASCII.GetString(toEncrypt)}");
Console.WriteLine($"Encrypted data: {Encoding.ASCII.GetString(toEncrypt)}");
Console.WriteLine("Decrypting...");

// Decrypt the data in memory.
DecryptInMemoryData(toEncrypt, MemoryProtectionScope.SameLogon);

Console.WriteLine($"Decrypted data: {UnicodeEncoding.ASCII.GetString(toEncrypt)}");
Console.WriteLine($"Decrypted data: {Encoding.ASCII.GetString(toEncrypt)}");

///////////////////////////////
//
Expand All @@ -42,7 +39,7 @@ public static void Run()
///////////////////////////////

// Create the original data to be encrypted
toEncrypt = UnicodeEncoding.ASCII.GetBytes("This is some data of any length.");
toEncrypt = Encoding.ASCII.GetBytes("This is some data of any length.");

// Create a file.
FileStream fStream = new FileStream("Data.dat", FileMode.OpenOrCreate);
Expand All @@ -51,7 +48,7 @@ public static void Run()
byte[] entropy = CreateRandomEntropy();

Console.WriteLine();
Console.WriteLine($"Original data: {UnicodeEncoding.ASCII.GetString(toEncrypt)}");
Console.WriteLine($"Original data: {Encoding.ASCII.GetString(toEncrypt)}");
Console.WriteLine("Encrypting and writing to disk...");

// Encrypt a copy of the data to the stream.
Expand All @@ -69,7 +66,7 @@ public static void Run()

fStream.Close();

Console.WriteLine($"Decrypted data: {UnicodeEncoding.ASCII.GetString(decryptData)}");
Console.WriteLine($"Decrypted data: {Encoding.ASCII.GetString(decryptData)}");
}
catch (Exception e)
{
Expand Down Expand Up @@ -172,4 +169,3 @@ public static byte[] DecryptDataFromStream(byte[] Entropy, DataProtectionScope S
return outBuffer;
}
}
// </snippet1>
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"host": "visualstudio"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{A4B12E1F-3C6D-4B25-9E5B-2E7D3A9F1B04}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>DataProtectionSample</RootNamespace>
<AssemblyName>DataProtectionSample</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<MyType>Console</MyType>
<StartupObject>DataProtectionSample.MemoryProtectionSample</StartupObject>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<OptionExplicit>On</OptionExplicit>
<OptionCompare>Binary</OptionCompare>
<OptionStrict>Off</OptionStrict>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>DataProtectionSample.xml</DocumentationFile>
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>DataProtectionSample.xml</DocumentationFile>
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Diagnostics" />
</ItemGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Security" />
</ItemGroup>
<ItemGroup>
<Compile Include="sample.vb" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
</Project>
Original file line number Diff line number Diff line change
@@ -1,42 +1,31 @@
' <snippet1>
Imports System.IO
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography



Public Module MemoryProtectionSample

Sub Main()
Run()

End Sub


Sub Run()
Try

''''''''''''''''''''''''''''''''''''
'
' Memory Encryption - ProtectedMemory
'
''''''''''''''''''''''''''''''''''''
' Create the original data to be encrypted (The data length should be a multiple of 16).
Dim toEncrypt As Byte() = UnicodeEncoding.ASCII.GetBytes("ThisIsSomeData16")
Dim toEncrypt As Byte() = Encoding.ASCII.GetBytes("ThisIsSomeData16")

Console.WriteLine("Original data: " + UnicodeEncoding.ASCII.GetString(toEncrypt))
Console.WriteLine("Original data: " + Encoding.ASCII.GetString(toEncrypt))
Console.WriteLine("Encrypting...")

' Encrypt the data in memory.
EncryptInMemoryData(toEncrypt, MemoryProtectionScope.SameLogon)

Console.WriteLine("Encrypted data: " + UnicodeEncoding.ASCII.GetString(toEncrypt))
Console.WriteLine("Encrypted data: " + Encoding.ASCII.GetString(toEncrypt))
Console.WriteLine("Decrypting...")

' Decrypt the data in memory.
DecryptInMemoryData(toEncrypt, MemoryProtectionScope.SameLogon)

Console.WriteLine("Decrypted data: " + UnicodeEncoding.ASCII.GetString(toEncrypt))
Console.WriteLine("Decrypted data: " + Encoding.ASCII.GetString(toEncrypt))


''''''''''''''''''''''''''''''''''''
Expand All @@ -45,7 +34,7 @@ Public Module MemoryProtectionSample
'
''''''''''''''''''''''''''''''''''''
' Create the original data to be encrypted
toEncrypt = UnicodeEncoding.ASCII.GetBytes("This is some data of any length.")
toEncrypt = Encoding.ASCII.GetBytes("This is some data of any length.")

' Create a file.
Dim fStream As New FileStream("Data.dat", FileMode.OpenOrCreate)
Expand All @@ -54,7 +43,7 @@ Public Module MemoryProtectionSample
Dim entropy As Byte() = CreateRandomEntropy()

Console.WriteLine()
Console.WriteLine("Original data: " + UnicodeEncoding.ASCII.GetString(toEncrypt))
Console.WriteLine("Original data: " + Encoding.ASCII.GetString(toEncrypt))
Console.WriteLine("Encrypting and writing to disk...")

' Encrypt a copy of the data to the stream.
Expand All @@ -72,18 +61,15 @@ Public Module MemoryProtectionSample

fStream.Close()

Console.WriteLine("Decrypted data: " + UnicodeEncoding.ASCII.GetString(decryptData))

Console.WriteLine("Decrypted data: " + Encoding.ASCII.GetString(decryptData))

Catch e As Exception
Console.WriteLine("ERROR: " + e.Message)
End Try

End Sub



Sub EncryptInMemoryData(ByVal Buffer() As Byte, ByVal Scope As MemoryProtectionScope)
Sub EncryptInMemoryData(Buffer() As Byte, Scope As MemoryProtectionScope)
If Buffer Is Nothing Then
Throw New ArgumentNullException("Buffer")
End If
Expand All @@ -96,8 +82,7 @@ Public Module MemoryProtectionSample

End Sub


Sub DecryptInMemoryData(ByVal Buffer() As Byte, ByVal Scope As MemoryProtectionScope)
Sub DecryptInMemoryData(Buffer() As Byte, Scope As MemoryProtectionScope)
If Buffer Is Nothing Then
Throw New ArgumentNullException("Buffer")
End If
Expand All @@ -110,7 +95,6 @@ Public Module MemoryProtectionSample

End Sub


Function CreateRandomEntropy() As Byte()
' Create a byte array to hold the random value.
Dim entropy(15) As Byte
Expand All @@ -126,9 +110,7 @@ Public Module MemoryProtectionSample

End Function 'CreateRandomEntropy



Function EncryptDataToStream(ByVal Buffer() As Byte, ByVal Entropy() As Byte, ByVal Scope As DataProtectionScope, ByVal S As Stream) As Integer
Function EncryptDataToStream(Buffer() As Byte, Entropy() As Byte, Scope As DataProtectionScope, S As Stream) As Integer
If Buffer Is Nothing Then
Throw New ArgumentNullException("Buffer")
End If
Expand Down Expand Up @@ -161,8 +143,7 @@ Public Module MemoryProtectionSample

End Function 'EncryptDataToStream


Function DecryptDataFromStream(ByVal Entropy() As Byte, ByVal Scope As DataProtectionScope, ByVal S As Stream, ByVal Length As Integer) As Byte()
Function DecryptDataFromStream(Entropy() As Byte, Scope As DataProtectionScope, S As Stream, Length As Integer) As Byte()
If S Is Nothing Then
Throw New ArgumentNullException("S")
End If
Expand All @@ -176,7 +157,6 @@ Public Module MemoryProtectionSample
Throw New ArgumentException("Entropy")
End If


Dim inBuffer(Length - 1) As Byte
Dim outBuffer() As Byte

Expand All @@ -194,4 +174,3 @@ Public Module MemoryProtectionSample

End Function 'DecryptDataFromStream
End Module 'MemoryProtectionSample
' </snippet1>
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"host": "visualstudio"
}
Loading
Loading