CryptographicException “Key not valid for use in specified state.” while trying to export RSAParameters of a X509 private key

后端 未结 7 1627
悲&欢浪女
悲&欢浪女 2020-12-03 06:34

I am staring at this for quite a while and thanks to the MSDN documentation I cannot really figure out what\'s going. Basically I am loading a PFX file from the disc into a

7条回答
  •  暖寄归人
    2020-12-03 06:53

    AFAIK this should work and you're likely hitting a bug/some limitations. Here's some questions that may help you figure out where's the issue.

    • How did you create the PKCS#12 (PFX) file ? I've seen some keys that CryptoAPI does not like (uncommon RSA parameters). Can you use another tool (just to be sure) ?

    • Can you export the PrivateKey instance to XML, e.g. ToXmlString(true), then load (import) it back this way ?

    • Old versions of the framework had some issues when importing a key that was a different size than the current instance (default to 1024 bits). What's the size of your RSA public key in your certificate ?

    Also note that this is not how you should encrypt data using RSA. The size of the raw encryption is limited wrt the public key being used. Looping over this limit would only give you really bad performance.

    The trick is to use a symmetric algorithm (like AES) with a totally random key and then encrypt this key (wrap) using the RSA public key. You can find C# code to do so in my old blog entry on the subject.

提交回复
热议问题