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