Question Decrypt docum. with x509Certificate2, preset passw. to suppress passw. dialog


New member
Mar 22, 2013
Programming Experience

I want to decrypt an Document with the matching private key under Windows high security conditions. But everytime the CSP asks for the password to grant access.

I need to suppress the password dialog and insert the password programmatically.


I have installed the X509 software certificate in certificate store under high security conditions. I fetched it as X509Certificates2 from store, encryption works, decryption works but password dialog appears. How can I set the password beforehand, so that it is already known by CSP and the access to private key operations will be granted, without password dialog?

Full story.

I tried following steps:
1. Encryption with x509 software certificate (public key)
The x509 certificate (cert) has been importet from the certificate store

    Public Function EncryptWithCertPubKey(cert As System.Security.Cryptography.X509Certificates.X509Certificate2, data As Byte()) As Byte()
        Dim rsa As System.Security.Cryptography.RSACryptoServiceProvider = TryCast(cert.PublicKey.Key, System.Security.Cryptography.RSACryptoServiceProvider)
        Return rsa.Encrypt(data, True)
    End Function

2. Decryption with x509 software certificate (private key)
The password (certPass) was set when installing the certificate into the certificate store under high security conditions.
The export to raw data seemed to be a way to do this and simutanously put in the password for suppressing the dialog.

    Public Function DecryptWithCertKey(cert As System.Security.Cryptography.X509Certificates.X509Certificate2, certPass As String, data As Byte()) As Byte()
        Dim rawdata As Byte() = cert.Export(Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, certPass)
        Dim cert2 As New System.Security.Cryptography.X509Certificates.X509Certificate2(rawdata, certPass)
        Dim rsa2 As System.Security.Cryptography.RSACryptoServiceProvider = TryCast(cert2.PrivateKey, System.Security.Cryptography.RSACryptoServiceProvider)
        Return rsa2.Decrypt(data, True)
    End Function

But again the password dialog appears while accessing the private key, event though the pass is given already.
cert.Export(Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, certPass)

I found out that there is a Function in CSP-Parameters to preset the Password, so it should be already known for the CSP, and no dialog might appear if it works.

Dim certPass As New System.Security.SecureString
Dim cspp As New System.Security.Cryptography.CspParameters(1, "Microsoft Strong Cryptographic Provider")
cspp.KeyPassword = certPass

But I don't know how to handle it, because I have'nt found a way to insert CSP-Parameters to X509Certificates2, neither to RSACryptoprovider (while using X509Certificates2).

Any help is appreciated. :confused:
Top Bottom