DataProtectionPermission Class

Note: This class is new in the .NET Framework version 2.0.

Controls the ability to access encrypted data and memory. This class cannot be inherited.

Namespace: System.Security.Permissions
Assembly: System.Security (in system.security.dll)

'Declaration
<SerializableAttribute> _
Public NotInheritable Class DataProtectionPermission
	Inherits CodeAccessPermission
	Implements IUnrestrictedPermission
'Usage
Dim instance As DataProtectionPermission

/** @attribute SerializableAttribute() */ 
public final class DataProtectionPermission extends CodeAccessPermission implements IUnrestrictedPermission
SerializableAttribute 
public final class DataProtectionPermission extends CodeAccessPermission implements IUnrestrictedPermission

This permission is used to control the ability to encrypt data and memory using the ProtectedData and ProtectedMemory classes.

The following code example shows the use of members of the DataProtectionPermission class.

Imports System
Imports System.Security.Permissions
Imports System.Security.Cryptography
Imports System.Security
Imports System.IO

<Assembly: DataProtectionPermission( _
    SecurityAction.RequestMinimum, _
    Flags:=DataProtectionPermissionFlags.ProtectData)> 

Public Class Form1
    Inherits System.Windows.Forms.Form

    ' Create a byte array for additional entropy when using the Protect
    ' and Unprotect methods.
    Private s_aditionalEntropy() As Byte = {9, 8, 7, 6, 5}

    Private encryptedSecret() As Byte
    Private originalData() As Byte

    ' Event handler for Run button.
    Private Sub Button1_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click

        tbxOutput.Cursor = Cursors.WaitCursor
        tbxOutput.Text = ""

        Write("Creating a permission with the Flags property = ")
        WriteLine("ProtectData.")
        Dim sp As New DataProtectionPermission( _
            DataProtectionPermissionFlags.ProtectData)
        ' Deny the permission to protect data.
        sp.Deny()
        ' The following code results in an exception due to an attempt
        ' to protect data.
        ProtectData()
        ' Remove the Deny for ProtectData permission.
        CodeAccessPermission.RevertDeny()
        ' The call to protect data will now succeed.
        ProtectData()
        Dim sp2 As New DataProtectionPermission( _
            DataProtectionPermissionFlags.UnprotectData)
        sp2.Deny()
        ' The following code results in an exception due to an attempt
        ' to unprotect data.
        UnprotectData()
        ' Remove the Deny for UnprotectData permission.
        CodeAccessPermission.RevertDeny()

        UnprotectData()
        ' Demonstrate the attribute.
        TryProtectData()
        ' Demonstrate the behavior of the class members.
        ShowMembers()

        ' Reset the cursor and conclude application.
        WriteLine(vbCrLf + "This sample completed successfully;" + _
            " press Exit to continue.")
        tbxOutput.Cursor = Cursors.Default
    End Sub

    'Deny the permission the ability to add to a store.
    <DataProtectionPermission( _
        SecurityAction.Deny, _
        Flags:=DataProtectionPermissionFlags.ProtectData)> _
    Private Sub TryProtectData()
        Try
            ProtectData()
        Catch ex As SecurityException
            Dim protectionPermission As DataProtectionPermission
            protectionPermission = _
                CType(ex.DenySetInstance, DataProtectionPermission)

            WriteLine("Security exception thrown when attempting: " + _
                protectionPermission.Flags.ToString())
        End Try
    End Sub
    ' The following method is intended to demonstrate only the behavior of
    ' DataProtectionPermission class members,and not their practical usage.
    ' Most properties and methods in this class are used for the resolution
    ' and enforcement of security policy by the security infrastructure code.
    Private Sub ShowMembers()
        WriteLine("Creating four DataProtectionPermissions.")
        Write("Creating the first permission with the Flags property = ")
        WriteLine("ProtectData.")
        Dim sp1 As New DataProtectionPermission( _
            DataProtectionPermissionFlags.ProtectData)

        Write("Creating the second permission with the Flags property = ")
        WriteLine("AllFlags.")
        Dim sp2 As New DataProtectionPermission( _
            DataProtectionPermissionFlags.AllFlags)

        Write("Creating the third permission with a permission state = ")
        WriteLine("Unrestricted.")
        Dim sp3 As New DataProtectionPermission(PermissionState.Unrestricted)
        Write("Creating the fourth permission with a permission state = ")
        WriteLine("None.")
        Dim sp4 As New DataProtectionPermission(PermissionState.None)

        Write("Is the permission with all flags set (AllFlags) a subset of ")
        Write("the permission with an Unrestricted permission state?")
        If (sp2.IsSubsetOf(sp3)) Then
            WriteLine("Yes")
        Else
            WriteLine("No")
        End If

        Write("Is the permission with ProtectData access a subset of the")
        Write(" permission with AllFlags set? ")
        If (sp1.IsSubsetOf(sp2)) Then
            WriteLine("Yes")
        Else
            WriteLine("No")
        End If

        Write("Is the third permission unrestricted? ")
        If (sp3.IsUnrestricted()) Then
            WriteLine("Yes")
        Else
            WriteLine("No")
        End If

        WriteLine("Copying the second permission to the fourth permission.")
        sp4 = CType(sp2.Copy(), DataProtectionPermission)

        Write("Is the fourth permission equal to the second permission? ")
        If (sp4.Equals(sp2)) Then
            WriteLine("Yes")
        Else
            WriteLine("No")
        End If

        Write("Creating the intersection of the second and first")
        WriteLine("permissions.")
        sp4 = CType(sp2.Intersect(sp1), DataProtectionPermission)
        WriteLine("The value of the Flags property is: " + _
            sp4.Flags.ToString())

        WriteLine("Creating the union of the second and first permissions.")
        sp4 = CType(sp2.Union(sp1), DataProtectionPermission)
        Write("Result of the union of the second permission with the first: ")
        WriteLine(sp4.Flags.ToString())

        WriteLine("Using an XML roundtrip to reset the fourth permission.")
        sp4.FromXml(sp2.ToXml())
        Write("Does the XML roundtrip result equal the original permission? ")
        If (sp4.Equals(sp2)) Then
            WriteLine("Yes")
        Else
            WriteLine("No")
        End If
    End Sub

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

        ' Encrypt the data.
        encryptedSecret = Protect(secret)
        If (Not encryptedSecret Is Nothing) Then
            WriteLine("The encrypted byte array is:")
            PrintValues(encryptedSecret)
        End If
    End Sub

    ' Decrypt the data and store in a byte array.
    Public Sub UnprotectData()
        originalData = Unprotect(encryptedSecret)

        If (Not originalData Is Nothing) Then
            WriteLine("The original data is:" + Environment.NewLine)
            PrintValues(originalData)
        End If
    End Sub

    ' Encrypt data in the specified byte array.
    Public Function Protect(ByVal data() As Byte) As Byte()
        Try
            ' Encrypt the data using DataProtectionScope.CurrentUser. The
            ' result can be decrypted only by the user who encrypted the data.
            Return ProtectedData.Protect( _
                data, _
                s_aditionalEntropy, _
                DataProtectionScope.CurrentUser)

        Catch ex As CryptographicException
            WriteLine("Data was not encrypted. An error has occurred.")
            WriteLine(ex.ToString())
            Return Nothing

        Catch securityException As SecurityException
            WriteLine("Insufficient permissions. An error has occurred.")
            WriteLine(securityException.ToString())
            Return Nothing

        End Try
    End Function
    Public Function Unprotect(ByVal data() As Byte) As Byte()
        Try
            ' Decrypt the data using DataProtectionScope.CurrentUser.
            ' The result can be decrypted only by the same current user.
            Return ProtectedData.Unprotect( _
                data, _
                s_aditionalEntropy, _
                DataProtectionScope.CurrentUser)

        Catch ex As CryptographicException
            WriteLine("Data was not decrypted. An error has occurred.")
            WriteLine(ex.ToString())
            Return Nothing

        Catch securityException As SecurityException
            WriteLine("Insufficient permissions. An error has occurred.")
            WriteLine(securityException.ToString())
            Return Nothing

        End Try
    End Function
    Public Sub PrintValues(ByVal myArr() As Byte)
        For Each i As Byte In myArr
            Write("    " + i.ToString())
        Next
        WriteLine("")
    End Sub
    ' Write the specified message and a carriage return to the output textbox.
    Private Sub WriteLine(ByVal message As String)
        tbxOutput.AppendText(message + vbCrLf)
    End Sub
    ' Write the specified message to the output textbox.
    Private Sub Write(ByVal message As String)
        tbxOutput.AppendText(message)
    End Sub

    ' Event handler for Exit button.
    Private Sub Button2_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button2.Click

        Application.Exit()
    End Sub
#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents Panel2 As System.Windows.Forms.Panel
    Friend WithEvents Panel1 As System.Windows.Forms.Panel
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents Button2 As System.Windows.Forms.Button
    Friend WithEvents tbxOutput As System.Windows.Forms.RichTextBox
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.Panel2 = New System.Windows.Forms.Panel
        Me.Button1 = New System.Windows.Forms.Button
        Me.Button2 = New System.Windows.Forms.Button
        Me.Panel1 = New System.Windows.Forms.Panel
        Me.tbxOutput = New System.Windows.Forms.RichTextBox
        Me.Panel2.SuspendLayout()
        Me.Panel1.SuspendLayout()
        Me.SuspendLayout()
        '
        'Panel2
        '
        Me.Panel2.Controls.Add(Me.Button1)
        Me.Panel2.Controls.Add(Me.Button2)
        Me.Panel2.Dock = System.Windows.Forms.DockStyle.Bottom
        Me.Panel2.Location = New System.Drawing.Point(0, 277)
        Me.Panel2.Name = "Panel2"
        Me.Panel2.Padding = New System.Windows.Forms.Padding(20)
        Me.Panel2.Size = New System.Drawing.Size(513, 56)
        Me.Panel2.TabIndex = 1
        '
        'Button1
        '
        Me.Button1.Dock = System.Windows.Forms.DockStyle.Right
        Me.Button1.Font = New System.Drawing.Font( _
            "Microsoft Sans Serif", _
            9.0!, _
            System.Drawing.FontStyle.Regular, _
            System.Drawing.GraphicsUnit.Point, _
            CType(0, Byte))
        Me.Button1.Location = New System.Drawing.Point(368, 20)
        Me.Button1.MinimumSize = New System.Drawing.Size(0, 20)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(62, 20)
        Me.Button1.TabIndex = 2
        Me.Button1.Text = "&Run"
        '
        'Button2
        '
        Me.Button2.Dock = System.Windows.Forms.DockStyle.Right
        Me.Button2.Font = New System.Drawing.Font( _
            "Microsoft Sans Serif", _
            9.0!, _
            System.Drawing.FontStyle.Regular, _
            System.Drawing.GraphicsUnit.Point, _
            CType(0, Byte))
        Me.Button2.Location = New System.Drawing.Point(430, 20)
        Me.Button2.MinimumSize = New System.Drawing.Size(0, 20)
        Me.Button2.Name = "Button2"
        Me.Button2.Size = New System.Drawing.Size(63, 20)
        Me.Button2.TabIndex = 3
        Me.Button2.Text = "E&xit"
        '
        'Panel1
        '
        Me.Panel1.Controls.Add(Me.tbxOutput)
        Me.Panel1.Dock = System.Windows.Forms.DockStyle.Fill
        Me.Panel1.Location = New System.Drawing.Point(0, 0)
        Me.Panel1.Name = "Panel1"
        Me.Panel1.Padding = New System.Windows.Forms.Padding(20)
        Me.Panel1.Size = New System.Drawing.Size(513, 277)
        Me.Panel1.TabIndex = 2
        '
        'tbxOutput
        '
        Me.tbxOutput.AccessibleDescription = _
            "Displays output from application."
        Me.tbxOutput.AccessibleName = "Output textbox."
        Me.tbxOutput.Dock = System.Windows.Forms.DockStyle.Fill
        Me.tbxOutput.Location = New System.Drawing.Point(20, 20)
        Me.tbxOutput.Name = "tbxOutput"
        Me.tbxOutput.Size = New System.Drawing.Size(473, 237)
        Me.tbxOutput.TabIndex = 1
        Me.tbxOutput.Text = "Click the Run button to run the application."
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(513, 333)
        Me.Controls.Add(Me.Panel1)
        Me.Controls.Add(Me.Panel2)
        Me.Name = "Form1"
        Me.Text = "DataProtectionPermission"
        Me.Panel2.ResumeLayout(False)
        Me.Panel1.ResumeLayout(False)
        Me.ResumeLayout(False)

    End Sub

#End Region
End Class

import System.*;
import System.Security.Permissions.*;
import System.Security.Cryptography.*;
import System.Security.*;
import System.IO.*;

/** @assembly DataProtectionPermission(SecurityAction.RequestMinimum, 
    Flags = DataProtectionPermissionFlags.ProtectData)
 */
public class DataProtect
{
    // Create a byte array for additional entropy when using the
    // Protect and Unprotect methods.
    private static ubyte s_aditionalEntropy[] =  { 9, 8, 7, 6, 5 };
    private static ubyte encryptedSecret[];
    private static ubyte originalData[];

    public static void main(String[] args)
    {
        Console.WriteLine("Creating a permission with the Flags property =" 
            + " ProtectData.");
        DataProtectionPermission sp = new DataProtectionPermission(
            DataProtectionPermissionFlags.ProtectData);

        // Deny the permission to protect data.
        sp.Deny();
        // The following code results in an exception due to an attempt to
        // protect data.
        ProtectData();
        // Remove the Deny for ProtectData permission.
        CodeAccessPermission.RevertDeny();
        // The call to protect data will now succeed.
        ProtectData();
        DataProtectionPermission sp2 = new DataProtectionPermission(
            DataProtectionPermissionFlags.UnprotectData);
        sp2.Deny();
        // The following code results in an exception due to an attempt
        // to unprotect data.
        UnprotectData();
        // Remove the Deny for UnprotectData permission.
        CodeAccessPermission.RevertDeny();

        UnprotectData();
        // Demonstrate the attribute.
        TryProtectData();
        // Demonstrate the behavior of the class members.
        ShowMembers();

        Console.WriteLine("Press the Enter key to exit.");
        Console.ReadKey();
        return;
    } //main

    //Deny the permission the ability to add to a store.
    /** @attribute DataProtectionPermission(SecurityAction.Deny, 
        Flags = DataProtectionPermissionFlags.ProtectData)
     */
    private static void TryProtectData()
    {
        try {
            ProtectData();
            return;
        }
        catch (System.Security.SecurityException e) {
            Console.WriteLine("A security exception thrown when attempting:" 
                + ((DataProtectionPermission)(e.get_DenySetInstance())).
                get_Flags());
            return;
        }
    } //TryProtectData

    // The following method is intended to demonstrate only the behavior of
    // DataProtectionPermission class members,and not their practical usage.
    // Most properties and methods in this class are used for the resolution
    // and enforcement of security policy by the security infrastructure code.
    private static void ShowMembers()
    {
        Console.WriteLine("Creating four DataProtectionPermissions");
        Console.WriteLine("Creating the first permission with the Flags " 
            + "property = ProtectData.");
        DataProtectionPermission sp1 = new DataProtectionPermission(
            DataProtectionPermissionFlags.ProtectData);

        Console.WriteLine("Creating the second permission with the Flags " 
            + "property = AllFlags.");

        DataProtectionPermission sp2 = new DataProtectionPermission(
            DataProtectionPermissionFlags.AllFlags);

        Console.WriteLine("Creating the third permission with a permission " 
            + "state = Unrestricted.");
        DataProtectionPermission sp3 = new DataProtectionPermission(
            PermissionState.Unrestricted);

        Console.WriteLine("Creating the fourth permission with a permission" 
            + " state = None.");

        DataProtectionPermission sp4 = new DataProtectionPermission(
            PermissionState.None);
        boolean rc = sp2.IsSubsetOf(sp3);
        Console.WriteLine("Is the permission with all flags set (AllFlags) " 
            + "a subset of \n \tthe permission with an Unrestricted " 
            + "permission state? " + ((rc) ? "Yes" : "No"));
        rc = sp1.IsSubsetOf(sp2);
        Console.WriteLine("Is the permission with ProtectData access a " 
            + "subset of the permission with \n" 
            + "\tAllFlags set? " + ((rc) ? "Yes" : "No"));

        rc = sp3.IsUnrestricted();
        Console.WriteLine("Is the third permission unrestricted? " 
            + ((rc) ? "Yes" : "No"));

        Console.WriteLine("Copying the second permission to the fourth " 
            + "permission.");
        sp4 = (DataProtectionPermission)(sp2.Copy());
        rc = sp4.Equals(sp2);
        Console.WriteLine("Is the fourth permission equal to the second " 
            + "permission? " 
            + ((rc) ? "Yes" : "No"));

        Console.WriteLine("Creating the intersection of the second and " 
            + "first permissions.");
        sp4 = (DataProtectionPermission)(sp2.Intersect(sp1));
        Console.WriteLine("The value of the Flags property is: " 
            + sp4.get_Flags().ToString());

        Console.WriteLine("Creating the union of the second and first " 
            + "permissions.");
        sp4 = (DataProtectionPermission)(sp2.Union(sp1));
        Console.WriteLine("Result of the union of the second permission " 
            + "with the first: " + sp4.get_Flags());

        Console.WriteLine("Using an XML round trip to reset the fourth " 
            + "permission.");
        sp4.FromXml(sp2.ToXml());
        rc = sp4.Equals(sp2);
        Console.WriteLine("Does the XML round trip result equal the " 
            + "original permission? " 
            + ((rc) ? "Yes" : "No"));
    } //ShowMembers

    // Create a simple byte array containing data to be encrypted.
    public static void ProtectData()
    {
        ubyte secret[] =  { 0, 1, 2, 3, 4, 1, 2, 3, 4 };
        //Encrypt the data.
        encryptedSecret = Protect(secret);
        Console.WriteLine("The encrypted byte array is:");
        if (encryptedSecret != null) {
            PrintValues(encryptedSecret);
        }
    } //ProtectData

    // Decrypt the data and store in a byte array.
    public static void UnprotectData()
    {
        originalData = Unprotect(encryptedSecret);
        if (originalData != null) {
            Console.WriteLine("\r\nThe original data is:");
            PrintValues(originalData);
        }
    } //UnprotectData

    // Encrypt data in the specified byte array.
    public static ubyte[] Protect(ubyte data[])
    {
        try {
            // Encrypt the data using DataProtectionScope.CurrentUser.
            // The result can be decrypted only by the user who encrypted
            // the data.
            return ProtectedData.Protect(data, s_aditionalEntropy,
                DataProtectionScope.CurrentUser);
        }
        catch (CryptographicException e) {
            Console.WriteLine("Data was not encrypted. " 
                + "An error has occurred.");
            Console.WriteLine(e.ToString());
            return null;
        }
        catch (System.Security.SecurityException e) {
            Console.WriteLine("Insufficient permissions. " 
                + "An error has occurred.");
            Console.WriteLine(e.ToString());
            return null;
        }
    } //Protect

    // Decrypt data in the specified byte array.
    public static ubyte[] Unprotect(ubyte data[])
    {
        try {
            //Decrypt the data using DataProtectionScope.CurrentUser.
            return ProtectedData.Unprotect(data, s_aditionalEntropy,
                DataProtectionScope.CurrentUser);
        }
        catch (CryptographicException e) {
            Console.WriteLine("Data was not decrypted. " 
                + "An error has occurred.");
            Console.WriteLine(e.ToString());
            return null;
        }
        catch (System.Security.SecurityException e) {
            Console.WriteLine("Insufficient permissions. " 
                + "An error has occurred.");
            Console.WriteLine(e.ToString());
            return null;
        }
    } //Unprotect

    public static void PrintValues(ubyte myArr[])
    {
        for (int iCtr = 0; iCtr < myArr.get_Length(); iCtr++) {
            ubyte i = myArr[iCtr];
            Console.Write("\t{0}", System.Convert.ToString(i));
        }
        Console.WriteLine();
    } //PrintValues
} //DataProtect 

System.Object
   System.Security.CodeAccessPermission
    System.Security.Permissions.DataProtectionPermission

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0

Community Additions

ADD
Show: