Home » .Net Framework

RSA crypto provider on compact framework 2.0 SP2 : Unknown exception when signing with sign key type

The RSA crypto provider on compact framework 2.0 SP2 is throwing an unknown exception when signing with sign key type. The full framework works fine.

Using an exchange key it works fine on both framework.


string message = "Tous les chats sont gris la nuit.";


            RSACryptoServiceProvider.UseMachineKeyStore = true;

            RSACryptoServiceProvider rsaCryptoServiceProvider = null;


            CspParameters parameters = newCspParameters();

            parameters.KeyContainerName = "TEST";

            parameters.KeyNumber = 2; //2 = forSignature; 1 = forExchanging

            parameters.Flags = CspProviderFlags.UseMachineKeyStore;




                rsaCryptoServiceProvider = newRSACryptoServiceProvider(parameters);


                rsaCryptoServiceProvider.PersistKeyInCsp = true;


                byte[] data = Encoding.UTF8.GetBytes(message);

                HashAlgorithm hasher = SHA1.Create(); // Our chosen hashing algorithm.


                // when the parameters.KeyNumber has forSignature value, I receive this

                // error : System.Security.Cryptography.CryptographicException was unhandled

                // Message="Unknown Error '80007015'."

                byte[] signedHash = rsaCryptoServiceProvider.SignData(data, hasher);







                if (rsaCryptoServiceProvider != null)

                    //remove it (we don't want garbage in our machine) this operation is performed

                    //  only for testing purpose.

                    rsaCryptoServiceProvider.PersistKeyInCsp = false;





Thanks for your help.


1 Answer Found


Answer 1

Is this happening with Windows Vista or Seven? or with Windows XP?

If the problem is happening with Vista or Seven, this post and the following codeplex proyect will help you:





I requested a Code Signing Certificate from my own domain Certification Authority on my Windows 2008 R2 domain controller.

When trying to publish my code to my webserver via Clickonce, it throws "an error occurred while signing: Invalid provider type specified"

In order to get the certificate I duplicated the Code Signing template on my CA, and tried both options available:

1) must use Microsoft Software Key Storage Provider

2) use any provider available locally

algorithm is RSA, key minim size 2048, Hash SHA1, alternative format unchecked


Using ASP .Net 4.0,Entity Framework and EntityDataSource.

I have some currency fields that are defined as Decimal. I would like to allow the user to enter a (leading) dollar sign in these (TextBox form fields). Although, when the EntityDataSource goes to save the changes to the datbase, it throws:

Error while setting property 'QuotedMaterial': 'Cannot convert the value of parameter 'QuotedMaterial' to the type 'System.Decimal'.'.

Does anyone know how I can "tell" the EF to allow dollar signs and convert (drop) them accordingly? I am trying to avoid creating my own Data or Business Logic layer for this particular application. I would like to stick with the EntityDataSource and other "built in" controls to minimize the C# code behind as much as possible.

I guess my only alternative is to deny $ (Dollar Signs) (and commas too for that mater, it doesn't like them either). The problem is I am porting a legacy application and I would like to keep it as close to the original as possible (and they are currently allowed to enter dollar signs in this application). You see, they use copy/paste for data entry quote often on this particular form and it just so happens that the source data (they are copy/pasting from) always has a $ in it...




Hello there.

I need to sign a data with a RSA signature that I have already generated on my local machine.

I generated the private key and from this generated a public key that I provided the receiving end with.

NOW I need to make sure that this private key is the key that I sign all my data with before sending it through the service.

Can I specify the key I should sign the data with in the "RSACryptoServiceProvider" somehow before I use the "SignData" function?



From my 2.0 .Net Framework App I need to sign a string with a X.509 certificate and the encryption algorithm for signing should be MD5/RSA. The resulting signature must be verified in a remote java app. Here's my methods to sign and verify the string:

public byte[] SignMessage(string Message)

 try {
  // Instantiate X509Certificate using file path
  X509Certificates.X509Certificate2 x509 = new X509Certificates.X509Certificate2(My.Settings.CertificatePath);

  // Convert Message to byte array
  byte[] data = Encoding.Unicode.GetBytes(Message);

  // Instantiate a RSA Algorithm object with Private Key
  RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509.PrivateKey;

  // Sign it
  // New MD5CryptoServiceProvider -> Instantiate the hash Algorithm to create the hash value.
  byte[] signature = rsa.SignData(data, new MD5CryptoServiceProvider());

  // Encode the Signature
  string Base64EncodededSignatureString = Convert.ToBase64String(signature, Base64FormattingOptions.None);

  // Return it as byte array
  return Encoding.Unicode.GetBytes(Base64EncodededSignatureString);


 } catch (Exception ex) {
  throw ex;



public bool VerifyMessage(string Message, byte[] signature)

 try {
  System.Text.UnicodeEncoding enc = new System.Text.UnicodeEncoding();

  // Get String form the siganture
  string strSignatureToVery = enc.GetString(signature);

  // 64Base Uncode the string signature
  byte[] DecodededSignature = Convert.FromBase64String(strSignatureToVery);

  // Convert to byte array the orignal Message string
  byte[] Data = Encoding.Unicode.GetBytes(Message);

  // Instantiate X509Certificate using file path
  X509Certificates.X509Certificate2 x509 = new X509Certificates.X509Certificate2(My.Settings.CertificatePath);

  // Instantiate a RSA Algorithm object with Public Key
  RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509.PublicKey.Key;

  // Verify Signature
  // New MD5CryptoServiceProvider -> Instantiate the hash Algorithm to create the hash value.
  return rsa.VerifyData(Data, new MD5CryptoServiceProvider(), DecodededSignature);

 } catch (Exception ex) {
  return false;



Here's an example of the strings I'm trying to sign :"bimusermbim_0300400000000000001CLI00300BIMSMS8240710051013089996019779996019779311720101011T16:30:16+0200"

And the resulting base64 signature is : "F4kFnD6K1AaqlO/AJ+UJd+40EIg+DCmOr9BgASGFSevf5ocr7BaKsr9sS107KdFGN6V+DZur+7ZGaiIsEIOwLph3L28sy/6m+Va0g+zWdcTpg+FAkuFI8MCULuYHNA8qPC+qdwSMnYS9fjAgS1boSyGe4+1dopdPiizyxLbEnE4="

The remote java application is from another company, with which we need to exchange this signatures,  and the java side the Encryption algorythm object is instantiated with the folowing Signature.getInstance("MD5withRSA"). And we both share the same X.509 certificate used in the signing mechanism.

I'm able to sign and verify with my previous methods on my 2.0 .Net environment , but when I pass the resulting signature to the Remote Java App it fails.

How can I achieve this interoperability?  Is my SignMessage method signing the string correctly?

Any help would be appreciatted,

Luis Pedro Ferreira



How to get localized sign in sign out buttons, I was going through http://msdn.microsoft.com/en-us/library/bb676638%28v=MSDN.10%29.aspx but I dint get any information there to localize the buttons. Any help would be appreciated

Thanks in advance


How to get localized sign in sign out buttons, I was going through http://msdn.microsoft.com/en-us/library/bb676638%28v=MSDN.10%29.aspx  but I dint get any information there to localize the buttons. Any help would be appreciated

Thanks in advance



I'm doing facebook authentication, and there is a method of authentication where they redirect back to my page with an auth_token in the QueryString.

The problem is the way it's done, instead of using a ? to conform with normal querystring convensions, they use a # sign...

So my querystring is as such : http://localhost/Default.aspx#access_token="..."&whatever_param=blah

What happens, is when my page is hit after authentication, all information after the # sign is stripped and I can't access the full querystring in code.

Is there a ways to do this?


Hi, I wondered if anyone else was having the same problem. I've got a bunch of Word templates that I created in Word 2003 on Windows XP Pro and signed successfully (that is, signing both the document and the macro code) using the StartSSL code signing certificate I generated using the instructions in the second post in this thread .

The trouble is that I'm now trying to edit them using Word 2007 on Windows 7. I added the signature successfully to my personal store and I can sign macro code using it, but when I try to sign the document (using the Office button -> Prepare -> Add a digital signature), all I get is a prompt telling me to get a digital ID from a Microsoft partner or create my own digital ID. Does anyone know how I can get round this issue?


I am logged on to the domain.  I open an ASP.Net page, hosted on a development machine, which redirects me to an ADFS2 server in the domain which prompts me for credentials.  Why, when I am already logged on?  Or is this not what single sign on means?

I would love to hear from anyone with a thought on this.


Hello All,

I enabled anonymous access on my SP 2010 foundation site. I want to hide ribbon for anonymous user. I used SPsecuritytrimcontrol to achive same and it worked for me. When I try log-in with administrator account it workes fine but when I try log-in with any other user account having read or contribute permission I am unable to see the ribbion.



o.k., i think i've done my homework and research, but my issue seems different from the ones others have posted.

i have a C# Solution built in VisualStudio 2010. i have a current, valid signing certificate from Thawte (and the intermediate chaining certs as well). i have imported the signing cert into my solution via Properties > Signing, "Sign the ClickOnce manifests" is checked, and i have imported the cert using "Select from Store...". (i also have an entry for the "Timestamp server URL".)

under "More Details..." > General, it says "You have a private key that corresponds to this certificate." under "Certification Path" it lists the chain: thawte > Thawte Code Signing CA - G2 > My Company Here, and Certificate status says: This certificate is OK.

so, everything seems to be in place, but when i build my .exe and .msi files, they are not signed.

i can manually run: "signtool.exe sign /a /t http://timestamp.verisign.com/scripts/timstamp.dll setup.exe" and the file is now signed correctly (i can also verify using signtool.exe), so i know the cert is valid, and works.

the only problem seems to be... VisualStudio will not do the signing for me. i currently have a workaround in place where i call signtool.exe as a Post-build event, but that's heavily dependent on file paths, etc... i would prefer a cleaner, automated solution.

so, i have a valid signing cert but my code is not being signed by VS2010. am i missing something here, or doing something wrong?


We're using delay signing in our projects and have post-build actions in every project that run sn -Vr on the produced assemblies so we can test and debug our code.  Once development is done we want to run sn -R on the resulting assemblies so they would be strongly signed and ready for packaging and release.  The problem we're running into is that we use denenv.com to run our release builds on our solutions, which ensures that once all projects are built successfully, the setup project gets built and produces our msi package.  How do we ensure that sn -R runs before the setup project begins to run?  It seems to me that we would need to use nant or MsBuild to achieve this.  BTW, We abandoned using MsBuild because it does not support setup projects withing vs solutions.  Any ideas?




I have a Infopath form with Digital Signatures implemented for some sections. Everything worked well in Moss 2007 SP1. Forms are opening in Web browser.

After installing SP2 When I try to sign some section I've got Infopath error dialog that just says "Error occured", no other errors, no errors in event viewer. If I click Continue everything works fine and I can sign my section.

Any clues or ideas?

Thanks in advance.


I am wondering if it is possible to do Single Sign On (SSO) or Pre-Logon Connect (PLC) for XP SP2?  I need to use the Microsoft Wireless Client, since I may have different wireless cards deployed, running on XP SP2.  Looking at the documentation, there seems to be 2 profiles available: Single Sign On Profile and Bootstrap Profile.  For the Wireless LAN API for Windows XP SP2, some of the elements do not seem applicable (like singleSignOn).

How can I do either SSO or PLC using the Microsoft Wireless Client on an XP SP2 system?  Is it at all possible using the Microsoft Wireless Client?  Can this be done programmatically?





I'm in the process of encrypting web.config on a number of servers.  Everythings been fine, except for one server in particular, which is refusing to encrypt the file.

The error I'm getting is :

D:\DOTNET\POREQ-IST>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pef connectionStrings .
Encrypting configuration section...
An error occurred executing the configuration section handler for connectionStrings.

Failed to encrypt the section 'connectionStrings' using provider 'RsaProtectedConfigurationProvider'. Error message from the provider: Safe handle has been closed

Now, I've checked the permissions to the RSA directory and they're fine (also used aspnet_regiis -pa to no success).  So, I figured I'd create a new key and try it that way, using aspnet_regiis -pc "testkey" -exp, and that is also coming up with 'safe handle has been closed'. 

No bother, so I thought I'd try and export the existing NetFrameworkConfigurationKey (also tried the 'testkey'), and still I'm getting the same error.

It does not appear to be a permissions issue as I've gone as far as setting 'Everyone' full access to the Crypto directory and all subfolders etc.  I also know that the creation command 'partly' works as a file is created in the RSA folder.

However, one thing I did notice is that both the new key AND the NetFrameworkConfigurationKey files are 1KB in size, and when looking inside them they look empty apart from the name a few characters into the first line (I know they're encoded, but looking at another server's there is actually visible data there) - so it almost looks like the key files on this server are corrupt.

Does anyone have any idea how to resolve this.  Is there a way to recreate the NetFrameworkConfigurationKey - as I suspect the encryption command is failing as the key effectively does not actually exist (basing this entirely on the fact that the file looks a bit weird).

Any help much appreciated,





Device : Windows Mobile 6.1 Classic / CE OS 5.2.20758 (Build 20758.1.4.1)

I installed SQL CF 3.5 SP2 on this device.

When I run an app ( written by C# CF) that uses SQL simple select statement with coalesce,

I got this error.

The specified argument value for the function is not valid.

[ Argument #= 1, Name of function (if known) = coalesce]


The strange thing is that...

When ran this exactly same app on the different device,

Device : Microsoft Pocket PC / Version 4.20.0 (Build 14053) / 1996 - 2003

It works fine without having any issue.

I even am able to run this app on the emulator without an issue.

Any idea?



In Firefox (I use 3.6.3 on Windows XP) when you press Esc key the WebMessenger Bar "mock" sign-out user. "Mock" because when user press Sign-in button again the WebMessenger Bar will sign-in user again.

Best regards,

Note: from stackoverflow: I think is better for system administrators.

I work in company with many servers and Pcs for developers. Servers are win2003, PC developers Windows XP.

In a server Win2003 named preiis01, in preproduction environment, other people in company install a client certificate using any other user (domainCompany\adminsystems) for logging in server preiis01.

Anyone admin uses the user "domainCompany\adminsystems" for log in server preiis01 (using Terminal Server, Remote Desktop for Windows XP).

the admin user is domainCompany\adminsystems", which installs certificate.

Admin user install it like this:

Session login like "domainCompany\adminsystems"
Certificate is PFX file. Do Install PFX and using Wizard. The key private not check for export.
Input the password and install.

There is an application Web which AppPool Identity is: NETWORK SERVICE account.

web server is IIS 6.0.

in preiis01,

That admin user executes mmc -> Snap in -> Certificates for Local Machine. In node -> Personal -> Certificates, he had seen the client certificate:


Issued By FNMT Clase 2 CA

In properties of certificate, the thumbprint: "93 bc a4 ad 58 c9 3c af 8b eb 0b 2f 86 c7 9d 81 70 a6 c4 13"

That admin user executes this commands:


Result is:

> Matching certificate:
> OU=703015476
> OU=FNMT Clase 2 CA
> C=ES
> Granting private key access for

Now, admin user executes this command:


The result is:

> Matching certificate:
> OU=703015476
> OU=FNMT Clase 2 CA
> C=ES
> Additional accounts and groups with
> access to the private key include: 
> domainCompany\adminsystems NT
> BUILTIN\Administrators NT

NOw, in an aspx page in application web in server Win2003, IIS 6.0, I have this code:

NOte: value for X509Certificate2.HasPrivateKeyAccess() is NO (false) for "ENTIDAD COMPANY SEGUROS GENERALES SA - CIF A93 - NOMBRE SURNAME1 NAME1" certificate.

ASP.NET application executes using the identity :: NT AUTHORITY\NETWORK SERVICE

    lbInfo.Text += "<br/><br/>ASP.NET application executes using the identity :: <b>" + WindowsIdentity.GetCurrent().Name + "</b><br>";
                var store = new X509Store(StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                Certificates = store.Certificates;
                repeater1.DataSource = Certificates;
                var nombreCertificado = "ENTIDAD COMPANY SEGUROS GENERALES SA - CIF A93 - NOMBRE SURNAME1 NAME1";
                store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindBySubjectName, nombreCertificado, false);
                if (col.Count > 0)
                    X509Certificate2 certificate = col[0];
                    Message.Text = "Certificado " + nombreCertificado + " encontrado en " + StoreLocation.LocalMachine;
                    FirmarConCertificado(nombreCertificado, certificate);
                    Message.Text = "El certificado " + nombreCertificado + " no esta instalado en la máquina";
    public void FirmarConCertificado(string nombreCertificado, X509Certificate2 certificate)
     var mensaje = "Datos de prueba";
                    System.Text.Encoding enc = System.Text.Encoding.Default;
                    byte[] data = enc.GetBytes(mensaje);
                    var contentInfo = new System.Security.Cryptography.Pkcs.ContentInfo(data);
                    var signedCms = new System.Security.Cryptography.Pkcs.SignedCms(contentInfo, true);
                    var cmsSigner = new System.Security.Cryptography.Pkcs.CmsSigner(certificate);
                    //  Sign the CMS/PKCS #7 message
                    //  Encode the CMS/PKCS #7 message
                   var ret = Convert.ToBase64String(signedCms.Encode());
     Message.Text += "Firmado con Certificado " + nombreCertificado + " encontrado en " + StoreLocation.LocalMachine;
     catch (Exception ex)
     Message.Text = "Error al firmar con certificado: " + ex.ToString();
     Message.Text += "<br /><br />InnerException: " + ex.InnerException;

The code fails for me, and I get this error: Cannot find the certificate and private key for decryption.

Error line is:signedCms.ComputeSignature(cmsSigner);

> Error al firmar con certificado:
> System.Security.Cryptography.CryptographicException:
> Cannot find the certificate and
> private key for decryption.
> at
> System.Security.Cryptography.Pkcs.PkcsUtils.CreateSignerEncodeInfo(CmsSigner
> signer, Boolean silent) at
> System.Security.Cryptography.Pkcs.SignedCms.Sign(CmsSigner
> signer, Boolean silent) at
> System.Security.Cryptography.Pkcs.SignedCms.ComputeSignature(CmsSigner
> signer, Boolean silent) at
> System.Security.Cryptography.Pkcs.SignedCms.ComputeSignature(CmsSigner
> signer) at
> ASP.dgsfp_test_testcert_aspx.FirmarConCertificado(String
> nombreCertificado, X509Certificate2
> certificate) in
> c:\Reale\NSI\DGSFP\DGSFP\Test\TestCert.aspx:line
> 242


Then, the admin user (I remember, who install the certificate) executes this commands:

> FindPrivateKey My LocalMachine -t "93
> bc a4 ad 58 c9 3c af 8b eb 0b 2f 86 c7
> 9d 81 70 a6 c4 13" –c   
> FindPrivateKey
> My LocalMachine -n "ENTIDAD COMPANY
> FindPrivateKey My LocalMachine -n
> –a

The result for all 3 commands is the same:

> FindPrivateKey helps user to find the
> location of the Private Key file of a
> X.50 9 Certificate.
> Usage: FindPrivateKey [{ {-n } | {-t }
> } [-f | -d | -a]]
>    <subjectName> subject name of the
> certificate
>    <thumbprint>  thumbprint of the
> certificate (use certmgr.exe to get
> it)
>    -f            output file name only
>    -d            output directory only
>    -a            output absolute file
> name e.g. FindPrivateKey My
> CurrentUser -n "CN=John Doe"
> e.g. FindPrivateKey My LocalMachine -t
> "03 33 98 63 d0 47 e7 48 71 33 62 64
> 76 5 c 4c 9d 42 1d 6b 52" -c

FindPrivateKey don't get anything, but winhttpcertcfg.exe -l works fine (matching certificate) 

We have given privileges to the Network Service user using the winhttpcertcfg.exe tool, and in code ASP.NET (execute under Network Service account) the certificate is found. But fails when sign using certificate.

If someone could give us some information about, or suggestions 


I have a WCF client calling a Java-based service. The service vendor is supporting WCF clients. The WCF client binding uses authenticationMode="MutualCertificate", messageVersion="Soap11WSAddressing10" and the message is signed and encrypted (SignBeforeEncrypt). WCF, in this case, is automatically signing all the ws-addressing ( <Action>, <MessageID> and <To> ) headers. The message gets to the service and comes back with what appears to be valid encrypted data in the response BUT the client is throwing a "The 'Action', 'http://www.w3.org/2005/08/addressing' required message part was not signed" exception (mscorlib).


Is there a way to NOT sign the ws-addressing headers in the request message while still using both signing and encryption (X.509 certs)?

If the client DOES sign the ws-addressing headers in the request, is there a way to configure WCF to accept UNsigned ws-addressing headers in the response?

If the answer is NO on both questions, I guess I will have to ask the service vendor to sign the ws-addressing headers in the response. Thanks.


I have VS 2008 SP1 and SQL Compact Compact 3.5 SP 1 installed.

I can see "ADO.NET Entity Data Model" when I go to Add -> New Item in Web Application project but same is not shown in Smart Device 2.0 application.

How to use Entity Framework (which version) with .NET CF 2.0 application and SQL Compact 3.5 SP 1?


<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure