Hinweis
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, sich anzumelden oder das Verzeichnis zu wechseln.
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, das Verzeichnis zu wechseln.
Note
Dieser Artikel bezieht sich auf Windows.
Informationen zu ASP.NET Core finden Sie unter ASP.NET Core Datenschutz.
.NET bietet Zugriff auf die Datenschutz-API (DPAPI), mit der Sie Daten mithilfe von Informationen aus dem aktuellen Benutzerkonto oder Computer verschlüsseln können. Wenn Sie die DPAPI verwenden, vermeiden Sie das schwierige Problem beim expliziten Generieren und Speichern eines kryptografischen Schlüssels.
Verwenden Sie die ProtectedData Klasse, um eine Kopie eines Bytearrays zu verschlüsseln. Sie können angeben, dass nur dasselbe Benutzerkonto die Daten entschlüsseln kann oder dass jedes Konto auf dem Computer sie entschlüsseln kann. Eine detaillierte Beschreibung der ProtectedData Optionen finden Sie in der DataProtectionScope Enumeration.
Verschlüsseln von Daten in einer Datei oder einem Datenstrom mithilfe des Datenschutzes
Erstellen Sie zufällige Entropie.
Rufen Sie die statische Protect-Methode auf und übergeben Sie dabei ein zu verschlüsselndes Byte-Array, den Entropiewert und den Schutzbereich.
Schreiben Sie die verschlüsselten Daten in eine Datei oder einen Datenstrom.
So entschlüsseln Sie Daten aus einer Datei oder einem Datenstrom mithilfe des Datenschutzes
Lesen Sie die verschlüsselten Daten aus einer Datei oder einem Datenstrom.
Rufen Sie die statische Unprotect-Methode auf, wobei Sie ein Array zu entschlüsselnder Bytes und den Datenschutzbereich übergeben.
Example
Das folgende Codebeispiel zeigt zwei Formen der Verschlüsselung und Entschlüsselung. Zuerst verschlüsselt der Code ein im Speicher befindliches Byte-Array und entschlüsselt es dann wieder. Als Nächstes verschlüsselt der Code eine Kopie eines Bytearrays, speichert sie in einer Datei, lädt die Daten aus der Datei zurück und entschlüsselt dann die Daten. Im Beispiel werden die ursprünglichen Daten, die verschlüsselten Daten und die entschlüsselten Daten angezeigt.
Important
ProtectedMemoryist nur für .NET Framework verfügbar. ProtectedDataist unter .NET und .NET Framework verfügbar.
Dieses Beispiel lässt sich kompilieren und ausführen, wenn Sie .NET unter Windows als Ziel verwenden. Um das Beispiel zu kompilieren, fügen Sie das System.Security.Cryptography.ProtectedData NuGet-Paket hinzu.
using System.Security.Cryptography;
using System.Text;
try
{
// Data Encryption - ProtectedData
// Create the original data to be encrypted.
byte[] toEncrypt = Encoding.ASCII.GetBytes("This is some data of any length.");
// Create some random entropy.
byte[] entropy = CreateRandomEntropy();
Console.WriteLine();
Console.WriteLine($"Original data: {Encoding.ASCII.GetString(toEncrypt)}");
Console.WriteLine("Encrypting and writing to disk...");
int bytesWritten;
// Encrypt a copy of the data to the stream.
using (FileStream writeStream = new("Data.dat", FileMode.OpenOrCreate))
{
bytesWritten = EncryptDataToStream(toEncrypt, entropy, DataProtectionScope.CurrentUser, writeStream);
}
Console.WriteLine("Reading data from disk and decrypting...");
// Read from the stream and decrypt the data.
byte[] decryptData;
using (FileStream readStream = new("Data.dat", FileMode.Open))
{
decryptData = DecryptDataFromStream(entropy, DataProtectionScope.CurrentUser, readStream, bytesWritten);
}
Console.WriteLine($"Decrypted data: {Encoding.ASCII.GetString(decryptData)}");
}
catch (Exception e)
{
Console.WriteLine($"ERROR: {e.Message}");
}
static byte[] CreateRandomEntropy()
{
// Create a byte array to hold the random value and fill it with a random value.
byte[] entropy = new byte[16];
RandomNumberGenerator.Fill(entropy);
return entropy;
}
static int EncryptDataToStream(byte[] buffer, byte[] entropy, DataProtectionScope scope, Stream stream)
{
ArgumentNullException.ThrowIfNull(buffer);
ArgumentOutOfRangeException.ThrowIfZero(buffer.Length, nameof(buffer));
ArgumentNullException.ThrowIfNull(entropy);
ArgumentOutOfRangeException.ThrowIfZero(entropy.Length, nameof(entropy));
ArgumentNullException.ThrowIfNull(stream);
int length = 0;
// Encrypt the data and store the result in a new byte array. The original data remains unchanged.
byte[] encryptedData = ProtectedData.Protect(buffer, entropy, scope);
// Write the encrypted data to a stream.
if (stream.CanWrite)
{
stream.Write(encryptedData, 0, encryptedData.Length);
length = encryptedData.Length;
}
// Return the length that was written to the stream.
return length;
}
static byte[] DecryptDataFromStream(byte[] entropy, DataProtectionScope scope, Stream stream, int length)
{
ArgumentNullException.ThrowIfNull(stream);
ArgumentOutOfRangeException.ThrowIfZero(length, nameof(length));
ArgumentNullException.ThrowIfNull(entropy);
ArgumentOutOfRangeException.ThrowIfZero(entropy.Length, nameof(entropy));
if (!stream.CanRead)
throw new IOException("Could not read the stream.");
byte[] inBuffer = new byte[length];
stream.ReadExactly(inBuffer, 0, length);
// Return the decrypted data.
return ProtectedData.Unprotect(inBuffer, entropy, scope);
}
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text
Public Module DataProtectionSample
Sub Main()
Try
' Data Encryption - ProtectedData
' Create the original data to be encrypted.
Dim toEncrypt As Byte() = Encoding.ASCII.GetBytes("This is some data of any length.")
' Create some random entropy.
Dim entropy As Byte() = CreateRandomEntropy()
Console.WriteLine()
Console.WriteLine($"Original data: {Encoding.ASCII.GetString(toEncrypt)}")
Console.WriteLine("Encrypting and writing to disk...")
Dim bytesWritten As Integer
' Encrypt a copy of the data to the stream.
Using writeStream As New FileStream("Data.dat", FileMode.OpenOrCreate)
bytesWritten = EncryptDataToStream(toEncrypt, entropy, DataProtectionScope.CurrentUser, writeStream)
End Using
Console.WriteLine("Reading data from disk and decrypting...")
' Read from the stream and decrypt the data.
Dim decryptData As Byte()
Using readStream As New FileStream("Data.dat", FileMode.Open)
decryptData = DecryptDataFromStream(entropy, DataProtectionScope.CurrentUser, readStream, bytesWritten)
End Using
Console.WriteLine($"Decrypted data: {Encoding.ASCII.GetString(decryptData)}")
Catch e As Exception
Console.WriteLine($"ERROR: {e.Message}")
End Try
End Sub
Function CreateRandomEntropy() As Byte()
' Create a byte array to hold the random value and fill it with a random value.
Dim entropy(15) As Byte
RandomNumberGenerator.Fill(entropy)
Return entropy
End Function
Function EncryptDataToStream(buffer As Byte(), entropy As Byte(), scope As DataProtectionScope, stream As Stream) As Integer
ArgumentNullException.ThrowIfNull(buffer)
ArgumentOutOfRangeException.ThrowIfZero(buffer.Length, NameOf(buffer))
ArgumentNullException.ThrowIfNull(entropy)
ArgumentOutOfRangeException.ThrowIfZero(entropy.Length, NameOf(entropy))
ArgumentNullException.ThrowIfNull(stream)
Dim length As Integer = 0
' Encrypt the data and store the result in a new byte array. The original data remains unchanged.
Dim encryptedData As Byte() = ProtectedData.Protect(buffer, entropy, scope)
' Write the encrypted data to a stream.
If stream.CanWrite Then
stream.Write(encryptedData, 0, encryptedData.Length)
length = encryptedData.Length
End If
' Return the length that was written to the stream.
Return length
End Function
Function DecryptDataFromStream(entropy As Byte(), scope As DataProtectionScope, stream As Stream, length As Integer) As Byte()
ArgumentNullException.ThrowIfNull(stream)
ArgumentOutOfRangeException.ThrowIfZero(length, NameOf(length))
ArgumentNullException.ThrowIfNull(entropy)
ArgumentOutOfRangeException.ThrowIfZero(entropy.Length, NameOf(entropy))
If Not stream.CanRead Then
Throw New IOException("Could not read the stream.")
End If
Dim inBuffer(length - 1) As Byte
stream.ReadExactly(inBuffer, 0, length)
' Return the decrypted data.
Return ProtectedData.Unprotect(inBuffer, entropy, scope)
End Function
End Module