none
RSACryptoServiceProvider error(s) RRS feed

  • General discussion

  • From a Windows From desktop application, Visual Studio 2008, framework 3.5

    I get errors trying to decrypt a message. I tried it different ways based on articles I found on the net, but I still have the same issues

    Heres common code to both approaches:

     

    UserCertX509Certificate2UI.SelectFromCollection(.....)

    RSACryptoServiceProvider pk = (RSACryptoServiceProvider)UserCert.PrivateKey;

    ....

    UserName = "Some Text";

    ...

    byte[] dcn = Encrypt(UserName, pkpub);

    ...

     

    Try #1

     

    string ptst = UserCert.PrivateKey.ToXmlString(true);  <-----------------  throws Key not valid for use in specified state

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

    byte[] decrypted;

    using (var rsaPublicPrivate = new RSACryptoServiceProvider())

    {

    rsaPublicPrivate.FromXmlString(key);

    decrypted = rsaPublicPrivate.Decrypt(data, false);

    }

    > mscorlib.dll!System.Security.Cryptography.CryptographicException.ThrowCryptogaphicException(int hr = -2146893813) Line 114 C#
      mscorlib.dll!System.Security.Cryptography.RSACryptoServiceProvider.ExportParameters(bool includePrivateParameters) Line 211 C#
      mscorlib.dll!System.Security.Cryptography.RSA.ToXmlString(bool includePrivateParameters = true) Line 138 C#

     

    Try #2 

     

    RSACryptoServiceProvider pk = (RSACryptoServiceProvider)UserCert.PrivateKey;

    byte[] decrypted;

    decrypted = pk.Decrypt(data, true);  <-------------- throws Invalid type specified.

     

      mscorlib.dll!System.Security.Cryptography.CryptographicException.ThrowCryptogaphicException(int hr = -2146893814) Line 114 C#
      mscorlib.dll!System.Security.Cryptography.RSACryptoServiceProvider.KeySize.get() Line 143 + 0xd bytes C#
      mscorlib.dll!System.Security.Cryptography.RSACryptoServiceProvider.Decrypt(byte[] rgb = {byte[128]}, bool fOAEP = true) Line 340 + 0xa bytes C#

    Monday, April 28, 2008 3:50 PM

All replies

  • if this isn't the correct place to post this, anyone point me to a place where I should?

     

     

    Tuesday, April 29, 2008 12:48 PM
  • Additional Information:

     

    One other thing I noticed after days of messing with this. I call :


    RSACryptoServiceProvider pkpriv = (RSACryptoServiceProvider)certs[0].PrivateKey;

    then I examined
    pkpriv.KeySize  in the watch window and it contains the exception I am seeing in the:

     

      base->base->_message = "Invalid type specified."

     

    Thursday, May 1, 2008 5:09 PM
  •  

    hello? anyone from Microsoft on this forum?
    Thursday, May 1, 2008 7:33 PM
  • What exactly you are trying for? It is not clear from your post. Is it something like this--?

    • A encrypts data and send it to B
    • B decrypts the Data
    ??? Please let me know your problem??
    Monday, May 26, 2008 3:23 AM
  • bobcary, if you still need help with this, please post a small repro which can be compiled and run (the smaller the better).
    Wednesday, July 8, 2009 6:03 AM
    Moderator
  • Hi All,
    I need help for this very problem. Here is what I am trying to achieve.
    Create a certificate using makecert.exe tool
    makecert -r -pe -n "CN=ciphertestcert1" -len 1024 -ss my -sr localMachine

    once done, then I used MMC and exported the created certificate with the option to have private key exportable. this creates a file
    ciphertestcert1.pfx

    then load the certificate in my Application
    new X509Certificate2(certPath);

    retrieve public key from this cert and encrypt a passphrase with it, save it to file.
    pubKeyAsXML = cert.PublicKey.Key.ToXmlString(false);// clpsCipherOps.getKeyAsXML(cert.GetPublicKey());
                    String encpassprase = ASCIIEncoding.ASCII.GetString(clpsCipherOps.rsaEncrypt(enc.GetBytes(passphrase),pubKeyAsXML,doOeapPadding));

    Here is the method to encrypt the passphrase using the public key, so far all seems to work.

    public byte[] rsaEncrypt(byte[] dataToEncrypt, String pubKeyInXml, bool doOeapPadding){
                try{
                    byte[] encryptedData;
                    RSACryptoServiceProvider rsacrypto = new RSACryptoServiceProvider();
                    rsacrypto.FromXmlString(pubKeyInXml);
                    rsacrypto.ExportParameters(false);
                    //writeToFile(dataToEncrypt,"beforeEnc.txt");
                    encryptedData = rsacrypto.Encrypt(dataToEncrypt, doOeapPadding);
                    writeToFile(encryptedData,"encrypted.dat");
                    return encryptedData;
                }catch (CryptographicException e){
                throw;
                }
            }

    My problem starts here, next step is use the same certificate, load its private key, to decrypt the passphrase encrypted in the previous step. And this is where I am stuck for past 1 day, I have used so many variants of the code below but nothing seem to work, all the documentation I read says that to retrieve a private key I need to do this
        RSACryptoServiceProvider rsapriv = ((RSACryptoServiceProvider) cert.PrivateKey);
        //rsapriv.ExportParameters(true);
        String keyAsXML = rsapriv.ToXmlString(true);

    However it always gives me an error
    "Key not valid for use in specified state"

    Can some one please help me out here?

    Thanks
    Thursday, September 24, 2009 6:30 PM
  • Ok, Hi all, again.
    I have figured out the issue.
    As I mentioned in the post above that I created the certificate using makecert.exe, then I used mmc.exe to export it as *.pfx file.
    This file I was loading using the following code

    new X509Certificate2(certPath);

    When I exported this to *.pfx file from mmc.exe, I would leave password empty and no X509KeyStorageFlags were set. Finally I have figured this now and here is what I did that made the whole thing work.

    X509KeyStorageFlags flags = X509KeyStorageFlags.Exportable;
    certWithPubKey = new X509Certificate2(certPath,"password",flags);

    So it seems that it requires a password as well as at the minimum the flag exportable be set.

    Thanks every one anyways...

    Thursday, September 24, 2009 7:44 PM
  • I am receiving a similar error. I'm not doing anything fancy here, just want to get at a public/private key pair for asymmetric encryption purposes.

    const int PROV_RSA_FULL = 1;
    
    using (var csp = new RSACryptoServiceProvider(keySize, new CspParameters
        {
            ProviderType = PROV_RSA_FULL,
            KeyNumber = (int) KeyNumber.Exchange,
            KeyPassword = password.AsSecureString(),
        }))
    {
        // TODO: use the csp details here.
        var withPrivate = csp.ToXmlString(true);
        var forPublic csp.ToXmlString(false);
    }

    Which as soon as the ToXmlString is called, I receive the same exception, "Invalid type specified".

    I wondered perhaps whether this was a service thing, so I restarted the Cryptographic Services but to no avail.

    I have also verified in my registry that indeed the those services are available.

    The keys are password protected with a String to SecureString conversion.

    Any suggestions what is going on here?

    Saturday, June 13, 2015 6:41 PM
  • Here's the exception detail as well...

    System.Security.Cryptography.CryptographicException occurred
      HResult=-2146893814
      Message=Invalid type specified.
    
      Source=mscorlib
      StackTrace:
           at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
           at System.Security.Cryptography.Utils.SetProviderParameter(SafeProvHandle hProv, Int32 keyNumber, UInt32 paramID, IntPtr pbData)
           at System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle)
           at System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()
           at System.Security.Cryptography.RSACryptoServiceProvider.ExportParameters(Boolean includePrivateParameters)
           at System.Security.Cryptography.RSA.ToXmlString(Boolean includePrivateParameters)
           at Kingdom.Security.Cryptography.AsymmetricUtilities.CreatePublicPrivateKeyPair(PublicPrivateKeyPair& pair, Int32 keySize, String password) in i:\Source\Kingdom Software\Football\Simulator\Kingdom.Security\Cryptography\AsymmetricUtilities.cs:line 28
      InnerException: 
    

    Saturday, June 13, 2015 6:43 PM
  • By process of elimination, it's not the ProviderType at all. It seems that as soon as I insert the SecureString, it chokes on that. Will need to dig a little bit to learn what to do with a password, besides a simple conversion to SecureString. It seems there is more involved with it than that.
    Saturday, June 13, 2015 7:07 PM