ProtectedData Klass

Definition

Innehåller metoder för att kryptera och dekryptera data. Det går inte att ärva den här klassen.

public ref class ProtectedData sealed
public ref class ProtectedData abstract sealed
public sealed class ProtectedData
public static class ProtectedData
type ProtectedData = class
Public NotInheritable Class ProtectedData
Public Class ProtectedData
Arv
ProtectedData

Exempel

I följande exempel visas hur du använder dataskydd.

using System;
using System.Security.Cryptography;

public class DataProtectionSample
{
    // Create byte array for additional entropy when using Protect method.
    static byte [] s_additionalEntropy = { 9, 8, 7, 6, 5 };

    public static void Main()
    {
        // Create a simple byte array containing data to be encrypted.
        byte [] secret = { 0, 1, 2, 3, 4, 1, 2, 3, 4 };

        //Encrypt the data.
        byte [] encryptedSecret = Protect( secret );
        Console.WriteLine("The encrypted byte array is:");
        PrintValues(encryptedSecret);

        // Decrypt the data and store in a byte array.
        byte [] originalData = Unprotect( encryptedSecret );
        Console.WriteLine("{0}The original data is:", Environment.NewLine);
        PrintValues(originalData);
    }

    public static byte [] Protect( byte [] data )
    {
        try
        {
            // Encrypt the data using DataProtectionScope.CurrentUser. The result can be decrypted
            // only by the same current user.
            return ProtectedData.Protect( data, s_additionalEntropy, DataProtectionScope.CurrentUser );
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("Data was not encrypted. An error occurred.");
            Console.WriteLine(e.ToString());
            return null;
        }
    }

    public static byte [] Unprotect( byte [] data )
    {
        try
        {
            //Decrypt the data using DataProtectionScope.CurrentUser.
            return ProtectedData.Unprotect( data, s_additionalEntropy, DataProtectionScope.CurrentUser );
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("Data was not decrypted. An error occurred.");
            Console.WriteLine(e.ToString());
            return null;
        }
    }

    public static void PrintValues( Byte[] myArr )
    {
        foreach ( Byte i in myArr )
        {
            Console.Write( "\t{0}", i );
        }
        Console.WriteLine();
    }
}
Imports System.Security.Cryptography



Public Class DataProtectionSample
    ' Create byte array for additional entropy when using Protect method.
    Private Shared s_additionalEntropy As Byte() = {9, 8, 7, 6, 5}


    Public Shared Sub Main()
        ' Create a simple byte array containing data to be encrypted.
        Dim secret As Byte() = {0, 1, 2, 3, 4, 1, 2, 3, 4}

        'Encrypt the data.
        Dim encryptedSecret As Byte() = Protect(secret)
        Console.WriteLine("The encrypted byte array is:")
        PrintValues(encryptedSecret)

        ' Decrypt the data and store in a byte array.
        Dim originalData As Byte() = Unprotect(encryptedSecret)
        Console.WriteLine("{0}The original data is:", Environment.NewLine)
        PrintValues(originalData)

    End Sub


    Public Shared Function Protect(ByVal data() As Byte) As Byte()
        Try
            ' Encrypt the data using DataProtectionScope.CurrentUser. The result can be decrypted
            '  only by the same current user.
            Return ProtectedData.Protect(data, s_additionalEntropy, DataProtectionScope.CurrentUser)
        Catch e As CryptographicException
            Console.WriteLine("Data was not encrypted. An error occurred.")
            Console.WriteLine(e.ToString())
            Return Nothing
        End Try

    End Function


    Public Shared Function Unprotect(ByVal data() As Byte) As Byte()
        Try
            'Decrypt the data using DataProtectionScope.CurrentUser.
            Return ProtectedData.Unprotect(data, s_additionalEntropy, DataProtectionScope.CurrentUser)
        Catch e As CryptographicException
            Console.WriteLine("Data was not decrypted. An error occurred.")
            Console.WriteLine(e.ToString())
            Return Nothing
        End Try

    End Function


    Public Shared Sub PrintValues(ByVal myArr() As [Byte])
        Dim i As [Byte]
        For Each i In myArr
            Console.Write(vbTab + "{0}", i)
        Next i
        Console.WriteLine()

    End Sub
End Class

Kommentarer

Den här klassen ger åtkomst till dataskydds-API :et (DPAPI) som är tillgängligt i Windows operativsystem. Det här är en tjänst som tillhandahålls av operativsystemet och som inte kräver ytterligare bibliotek. Det ger skydd med användarens eller datorns autentiseringsuppgifter för att kryptera eller dekryptera data.

Important

Eftersom det beror på DPAPI stöds klassen ProtectedData endast på Windows-plattformen. Dess användning på .NET Core på andra plattformar än Windows genererar en PlatformNotSupportedException.

Klassen består av två omslutningar för den ohanterade DPAPI: Protect en och Unprotect. Dessa två metoder kan användas för att kryptera och dekryptera data som lösenord, nycklar och anslutningssträngar.

Om du använder dessa metoder under personifieringen kan du få följande fel: "Nyckeln är inte giltig för användning i angivet tillstånd". Detta beror på att DPAPI lagrar nyckeldata i användarprofiler. Om profilen inte läses in kan DPAPI inte utföra dekrypteringen. Om du vill förhindra det här felet läser du in profilen för den användare som du vill personifiera innan du anropar någon av metoderna. Att använda DPAPI med personifiering kan medföra betydande komplikationer och kräver noggranna designval.

Metoder

Name Description
Protect(Byte[], Byte[], DataProtectionScope)

Krypterar data i en angiven bytematris och returnerar en bytematris som innehåller krypterade data.

Unprotect(Byte[], Byte[], DataProtectionScope)

Dekrypterar data i en angiven bytematris och returnerar en bytematris som innehåller de dekrypterade data.

Gäller för