CRYPTPROTECT_PROMPTSTRUCT Parameter error

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • DazedAndConfused

    #1

    CRYPTPROTECT_PROMPTSTRUCT Parameter error

    I converted a C# example of using dll crypt32 to VB .NET. The converted
    example fails when Encypting/Decypting. I found that if instead of defining
    a variable as and setting the values for CRYPTPROTECT_PR OMPTSTRUCT; I
    defined the variable as IntPtr and then set it to zero
    CryptProtectDat a/CryptUnrotectDa ta return without error.

    The values between the C# and VB for CRYPTPROTECT_PR OMPTSTRUCT are exact
    except for szPrompt C# passes null and VB passes nothing, but in both cases
    that is valid.

    I did come accross a good example of Encrypting/Decrypting in VB .NET that I
    can use and the values being passed for CRYPTPROTECT_PR OMPTSTRUCT are
    axactly the same as the code I am having the problem with.

    This is driving me nuts!! I know I am missing something, somewhere, but I
    just can not find the problem.


    In anybody can figure this out and tell me where I went wrong that would be
    great.


    DataProtect Class
    _______________ _______________ _______________ ______
    Imports System
    Imports System.Text
    Imports System.Runtime. InteropServices

    Public Class DataProtect

    <DllImport("cry pt32", SetLastError:=T rue, CharSet:=CharSe t.Auto)> _
    Private Shared Function CryptProtectDat a( _
    ByRef pDataIn As DATA_BLOB, _
    ByVal szDataDescr As String, _
    ByRef pOptionalEntrop y As DATA_BLOB, _
    ByVal pvReserved As IntPtr, _
    ByVal pPromptStruct As CRYPTPROTECT_PR OMPTSTRUCT, _
    ByVal dwFlags As Integer, _
    ByRef pDataOut As DATA_BLOB) As Boolean
    End Function

    <DllImport("cry pt32", SetLastError:=T rue, CharSet:=CharSe t.Auto)> _
    Public Shared Function CryptUnprotectD ata(ByRef _
    pDataIn As DATA_BLOB, _
    ByVal szDataDescr As String, _
    ByRef pOptionalEntrop y As DATA_BLOB, _
    ByVal pvReserved As IntPtr, _
    ByVal pPromptStruct As CRYPTPROTECT_PR OMPTSTRUCT, _
    ByVal dwFlags As Integer, _
    ByRef pDataOut As DATA_BLOB) As Boolean
    End Function

    <DllImport("ker nel32")> _
    Public Shared Function FormatMessage( _
    ByVal dwFlags As Integer, _
    ByRef lpSource As IntPtr, _
    ByVal dwMessageId As Integer, _
    ByVal dwLanguageId As Integer, _
    ByRef lpBuffer As String, _
    ByVal nsize As Integer, _
    ByVal Arguments As IntPtr) As Integer

    End Function

    <StructLayout(L ayoutKind.Seque ntial, CharSet:=CharSe t.Unicode)> _
    Public Structure DATA_BLOB
    Public cbData As Integer
    Public pbData As IntPtr
    End Structure

    ' Prompt structure to be used for required parameters.
    <StructLayout(L ayoutKind.Seque ntial, CharSet:=CharSe t.Unicode)> _
    Public Structure CRYPTPROTECT_PR OMPTSTRUCT
    Public cbSize As Integer
    Public dwPromptFlags As Integer
    Public hwndApp As IntPtr
    Public szPrompt As String
    End Structure

    Private Shared NullPtr As IntPtr = Nothing
    Public Const CRYPTPROTECT_UI _FORBIDDEN As Integer = &H1
    Public Const CRYPTPROTECT_LO CAL_MACHINE As Integer = &H4

    ' <summary>
    ' Initializes empty prompt structure.
    ' </summary>
    ' <param name="ps">
    ' Prompt parameter (which we do not actually need).
    ' </param>
    Private Shared Sub InitPromptStruc t _
    ( _
    ByRef ps As CRYPTPROTECT_PR OMPTSTRUCT _
    )
    ps.cbSize = Marshal.SizeOf( GetType(CRYPTPR OTECT_PROMPTSTR UCT))
    ps.dwPromptFlag s = 0
    ps.hwndApp = IntPtr.Zero
    ps.szPrompt = Nothing
    End Sub

    Public Enum Store
    USE_MACHINE_STO RE
    USE_USER_STORE
    End Enum

    Private myStore As Store
    Public Sub New(ByVal tempStore As Store)
    myStore = tempStore

    End Sub

    Public Function Encrypt(ByVal plainText As Byte(), _
    ByVal optionalEntropy As Byte()) As Byte()
    Dim retVal As Boolean = False
    Dim plainTextBlob As DATA_BLOB = New DATA_BLOB
    Dim cipherTextBlob As DATA_BLOB = New DATA_BLOB
    Dim entropyBlob As DATA_BLOB = New DATA_BLOB
    Dim prompt As CRYPTPROTECT_PR OMPTSTRUCT = New CRYPTPROTECT_PR OMPTSTRUCT
    Dim dwFlags As Integer
    InitPromptStruc t(prompt)
    Try
    Try
    Dim bytesSize As Integer = plainText.Lengt h
    plainTextBlob.p bData = Marshal.AllocHG lobal(bytesSize )
    If plainTextBlob.p bData.Equals(No thing) Then
    Throw New Exception("Unab le to allocate plaintext buffer.")
    End If
    plainTextBlob.c bData = bytesSize
    Marshal.Copy(pl ainText, 0, plainTextBlob.p bData, bytesSize)
    Catch ex As Exception
    Throw New Exception("Exce ption marshalling data. " + ex.Message)
    End Try
    If Store.USE_MACHI NE_STORE = myStore Then
    dwFlags = CRYPTPROTECT_LO CAL_MACHINE Or CRYPTPROTECT_UI _FORBIDDEN
    If Nothing Is optionalEntropy Then
    'Allocate something
    optionalEntropy = New Byte() {}
    End If

    Try
    Dim bytesSize As Integer = optionalEntropy .Length
    entropyBlob.pbD ata = Marshal.AllocHG lobal(optionalE ntropy.Length)
    If entropyBlob.Equ als(Nothing) Then
    Throw New Exception("Unab le to allocate entropy data buffer.")
    End If
    Marshal.Copy(op tionalEntropy, 0, entropyBlob.pbD ata, bytesSize)
    entropyBlob.cbD ata = bytesSize
    Catch ex As Exception
    Throw New Exception("Exce ption entropy marshalling data. " +
    ex.Message)
    End Try
    Else
    dwFlags = CRYPTPROTECT_UI _FORBIDDEN
    End If
    retVal = CryptProtectDat a(plainTextBlob , "", entropyBlob, IntPtr.Zero,
    prompt, dwFlags, cipherTextBlob)
    If retVal = False Then
    Throw New Exception("Encr yption failed. " +
    GetErrorMessage (Marshal.GetLas tWin32Error()))
    End If
    If Not IntPtr.Zero.Equ als(plainTextBl ob.pbData) Then
    Marshal.FreeHGl obal(plainTextB lob.pbData)
    End If
    If Not IntPtr.Zero.Equ als(entropyBlob .pbData) Then
    Marshal.FreeHGl obal(entropyBlo b.pbData)
    End If
    Catch ex As Exception
    Throw New Exception("Exce ption encrypting. " + ex.Message)
    End Try
    Dim cipherText(ciph erTextBlob.cbDa ta) As Byte
    Marshal.Copy(ci pherTextBlob.pb Data, cipherText, 0, cipherTextBlob. cbData)
    Marshal.FreeHGl obal(cipherText Blob.pbData)
    Return cipherText

    End Function
    Public Function Decrypt(ByVal cipherText() As Byte, ByVal optionalEntropy ()
    As Byte) As Byte()
    Dim retVal As Boolean = False
    Dim plainTextBlob As New DATA_BLOB
    Dim cipherBlob As New DATA_BLOB
    Dim prompt As New CRYPTPROTECT_PR OMPTSTRUCT
    InitPromptStruc t(prompt)

    Try
    Try
    Dim cipherTextSize As Integer = cipherText.Leng th
    cipherBlob.pbDa ta = Marshal.AllocHG lobal(cipherTex tSize)

    If cipherBlob.pbDa ta.Equals(Nothi ng) Then
    Throw New Exception("Unab le to allocate cipherText buffer.")
    End If

    cipherBlob.cbDa ta = cipherTextSize
    Marshal.Copy(ci pherText, 0, cipherBlob.pbDa ta, cipherBlob.cbDa ta)
    Catch ex As Exception
    Throw New Exception("Exce ption marshalling data. " + ex.Message)
    End Try

    Dim entropyBlob As New DATA_BLOB
    Dim dwFlags As Integer

    If Store.USE_MACHI NE_STORE = myStore Then
    ' Using the machine store, should be providing entropy.
    dwFlags = CRYPTPROTECT_LO CAL_MACHINE Or CRYPTPROTECT_UI _FORBIDDEN

    ' Check to see if the entropy is null
    If Nothing Is optionalEntropy Then
    'Allocate something
    optionalEntropy = New Byte() {}
    End If

    Try
    Dim bytesSize As Integer = optionalEntropy .Length
    entropyBlob.pbD ata = Marshal.AllocHG lobal(bytesSize )

    If entropyBlob.pbD ata.Equals(Noth ing) Then
    Throw New Exception("Unab le to allocate entropy buffer.")
    End If

    entropyBlob.cbD ata = bytesSize
    Marshal.Copy(op tionalEntropy, 0, entropyBlob.pbD ata, bytesSize)
    Catch ex As Exception
    Throw New Exception("Exce ption entropy marshalling data. " +
    ex.Message)
    End Try
    Else
    ' Using the user store
    dwFlags = CRYPTPROTECT_UI _FORBIDDEN
    End If

    retVal = CryptUnprotectD ata(cipherBlob, "", entropyBlob, IntPtr.Zero,
    prompt, dwFlags, plainTextBlob)

    If False = retVal Then
    Throw New Exception("Decr yption failed. " +
    GetErrorMessage (Marshal.GetLas tWin32Error()))
    End If

    ' Free the blob and entropy.
    If Not cipherBlob.pbDa ta.Equals(IntPt r.Zero) Then
    Marshal.FreeHGl obal(cipherBlob .pbData)
    End If

    If Not entropyBlob.pbD ata.Equals(IntP tr.Zero) Then
    Marshal.FreeHGl obal(entropyBlo b.pbData)
    End If
    Catch ex As Exception
    Throw New Exception("Exce ption decrypting. " + ex.Message)
    End Try

    Dim plainText(plain TextBlob.cbData ) As Byte
    Marshal.Copy(pl ainTextBlob.pbD ata, plainText, 0, plainTextBlob.c bData)
    Marshal.FreeHGl obal(plainTextB lob.pbData)
    Return plainText
    End Function 'Decrypt

    Private Shared Function GetErrorMessage (ByVal errorCode As Integer) As
    [String]
    Dim FORMAT_MESSAGE_ ALLOCATE_BUFFER As Integer = &H100
    Dim FORMAT_MESSAGE_ IGNORE_INSERTS As Integer = &H200
    Dim FORMAT_MESSAGE_ FROM_SYSTEM As Integer = &H1000
    Dim messageSize As Integer = 255
    Dim lpMsgBuf As [String] = ""
    Dim dwFlags As Integer = FORMAT_MESSAGE_ ALLOCATE_BUFFER Or
    FORMAT_MESSAGE_ FROM_SYSTEM Or FORMAT_MESSAGE_ IGNORE_INSERTS

    Dim ptrlpSource As New IntPtr
    Dim prtArguments As New IntPtr

    Dim retVal As Integer = FormatMessage(d wFlags, ptrlpSource, errorCode, 0,
    lpMsgBuf, messageSize, prtArguments)

    If 0 = retVal Then
    Throw New Exception("Fail ed to format message for error code " +
    CStr(errorCode) + ". ")
    End If
    Return lpMsgBuf
    End Function 'GetErrorMessag e

    End Class

    _______________ _______________ _______________ ___
    test form
    _______________ _______________ __________

    Imports System.text
    Public Class Form1
    Inherits System.Windows. Forms.Form

    #Region " Windows Form Designer generated code "

    Public Sub New()
    MyBase.New()

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

    'Add any initialization after the InitializeCompo nent() 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.Disp ose()
    End If
    End If
    MyBase.Dispose( disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.Componen tModel.IContain er

    '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 txtDataToEncryp t As System.Windows. Forms.TextBox
    Friend WithEvents lblError As System.Windows. Forms.Label
    Friend WithEvents btnEncypt As System.Windows. Forms.Button
    Friend WithEvents txtEncryptedDat a As System.Windows. Forms.TextBox
    <System.Diagnos tics.DebuggerSt epThrough()> Private Sub
    InitializeCompo nent()
    Me.txtDataToEnc rypt = New System.Windows. Forms.TextBox
    Me.txtEncrypted Data = New System.Windows. Forms.TextBox
    Me.lblError = New System.Windows. Forms.Label
    Me.btnEncypt = New System.Windows. Forms.Button
    Me.SuspendLayou t()
    '
    'txtDataToEncry pt
    '
    Me.txtDataToEnc rypt.Location = New System.Drawing. Point(16, 24)
    Me.txtDataToEnc rypt.Multiline = True
    Me.txtDataToEnc rypt.Name = "txtDataToEncry pt"
    Me.txtDataToEnc rypt.Size = New System.Drawing. Size(352, 20)
    Me.txtDataToEnc rypt.TabIndex = 0
    Me.txtDataToEnc rypt.Text = ""
    '
    'txtEncryptedDa ta
    '
    Me.txtEncrypted Data.Location = New System.Drawing. Point(16, 112)
    Me.txtEncrypted Data.Multiline = True
    Me.txtEncrypted Data.Name = "txtEncryptedDa ta"
    Me.txtEncrypted Data.Size = New System.Drawing. Size(352, 20)
    Me.txtEncrypted Data.TabIndex = 1
    Me.txtEncrypted Data.Text = ""
    '
    'lblError
    '
    Me.lblError.Aut oSize = True
    Me.lblError.Loc ation = New System.Drawing. Point(16, 192)
    Me.lblError.Nam e = "lblError"
    Me.lblError.Siz e = New System.Drawing. Size(0, 16)
    Me.lblError.Tab Index = 2
    '
    'btnEncypt
    '
    Me.btnEncypt.Lo cation = New System.Drawing. Point(16, 64)
    Me.btnEncypt.Na me = "btnEncypt"
    Me.btnEncypt.Ta bIndex = 3
    Me.btnEncypt.Te xt = "Encrypt"
    '
    '
    'Form1
    '
    Me.AutoScaleBas eSize = New System.Drawing. Size(5, 13)
    Me.ClientSize = New System.Drawing. Size(544, 266)
    Me.Controls.Add (Me.btnEncrypt3 )
    Me.Controls.Add (Me.btnEncypt2)
    Me.Controls.Add (Me.btnEncypt)
    Me.Controls.Add (Me.lblError)
    Me.Controls.Add (Me.txtEncrypte dData)
    Me.Controls.Add (Me.txtDataToEn crypt)
    Me.Name = "Form1"
    Me.Text = "Form1"
    Me.ResumeLayout (False)

    End Sub

    #End Region

    Private Sub btnEncypt_Click (ByVal sender As System.Object, ByVal e As
    System.EventArg s) Handles btnEncypt.Click
    Dim dp As New DataProtect(Dat aProtect.Store. USE_MACHINE_STO RE)

    Try
    Dim entropy As Byte() = Nothing
    Dim dataToEncrypt As Byte() =
    Encoding.UTF8.G etBytes(txtData ToEncrypt.Text)
    txtEncryptedDat a.Text = Convert.ToBase6 4String(dp.Encr ypt(dataToEncry pt,
    entropy))
    Catch ex As Exception
    lblError.ForeCo lor = System.Drawing. Color.Red
    lblError.Text = "Exception. " & Chr(13) & ex.Message
    Return
    End Try
    lblError.Text = ""
    End Sub


    End Class


  • Dragon

    #2
    Re: CRYPTPROTECT_PR OMPTSTRUCT Parameter error

    Hello,

    Change pPromptStruct parameter to ByRef in CryptProtectDat a &
    CryptUnprotectD ata.

    HTH,
    Roman


    Comment

    • DazedAndConfused

      #3
      Re: CRYPTPROTECT_PR OMPTSTRUCT Parameter error

      THANK YOU!!!!! Do you know where I can find a Dunce cap the size of a
      tent??? :)


      "Dragon" <no@spam.please > wrote in message
      news:OP10HDGxFH A.904@tk2msftng p13.phx.gbl...[color=blue]
      > Hello,
      >
      > Change pPromptStruct parameter to ByRef in CryptProtectDat a &
      > CryptUnprotectD ata.
      >
      > HTH,
      > Roman
      >
      >[/color]


      Comment

      Working...