views:

260

answers:

1

Scenario

I'm trying to use certificates to sign documents. The first time that I sign, the OS prompts a dialog for user to set the PIN, but the next times it doesn’t. For security reasons, I need that every time that I sign, the OS asks the PIN to the user. Anyone knows how to do that?

This is the code:

''// create ContentInfo
Dim content As New ContentInfo(bytesContenido)

''// create a signer
Dim signer As New CmsSigner(certificado)

''// SignedCms represents signed data
Dim signedMessage As New SignedCms(content)

''// sign the data
signedMessage.ComputeSignature(signer, False)

''// create and return PKCS #7 byte array
Return signedMessage.Encode()

On some pages I have found that using the CryptSetProvParam can clean the pin, but so far is not working.

The statement:

<DllImport("advapi32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
Public Shared Function CryptSetProvParam(ByVal hProv As IntPtr, ByVal dwParam As Int32, ByVal pbData As Byte(), ByVal dwFlags As Int32) As Boolean

End Function

The invocation:

Public punteroContexto As New System.IntPtr     ''// Obtenido usando CryptAcquireContext
Public Const PP_SIGNATURE_PIN As UInt32 = 33

If (Not CryptSetProvParam(punteroContexto, PP_SIGNATURE_PIN, Nothing, 0)) Then
    Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error)
End If

The error:

Invalid type specified. (Exception from HRESULT: 0x8009000A)

Also test using multithread (using another thread just for signing) and it doesn´t work.

Thank you very much!

A: 
[DllImport("Advapi32.dll", SetLastError = true)]
public static extern bool CryptSetProvParam(IntPtr hProv, uint dwParam, IntPtr pvData, uint dwFlags);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool CryptAcquireContext(ref IntPtr hProv,
    string pszContainer, string pszProvider, uint dwProvType, uint dwFlags);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern void CryptReleaseContext(IntPtr hProv, uint dwFlags);

static public bool ClearPINCache2(RSACryptoServiceProvider key)
{
    const uint PP_KEYEXCHANGE_PIN = 32;
    const uint PP_SIGNATURE_PIN = 33;
    bool bretval = false;

    IntPtr hProv = IntPtr.Zero;

    if (CryptAcquireContext(ref hProv, key.CspKeyContainerInfo.KeyContainerName,
        key.CspKeyContainerInfo.ProviderName, (uint)key.CspKeyContainerInfo.ProviderType, 0))
    {
        if ((CryptSetProvParam(hProv, PP_KEYEXCHANGE_PIN, IntPtr.Zero, 0) == true) &&
            (CryptSetProvParam(hProv, PP_SIGNATURE_PIN, IntPtr.Zero, 0) == true))
        {
            bretval = true;
        }
    }

    if (hProv != IntPtr.Zero)
    {
        CryptReleaseContext(hProv, 0);
        hProv = IntPtr.Zero;
    }

    return bretval;
}