Retired Microsoft Blog disclaimer

This directory is a mirror of retired "Decrypt My World" MSDN blog and is provided as is. All posting authorship and copyrights belong to respective authors.
Original URL: https://blogs.msdn.microsoft.com/alejacma/2008/10/23/rsacryptoserviceprovider-encrypt-returns-key-not-valid-for-use-in-specified-state-error/
Post name: RSACryptoServiceProvider.Encrypt returns "Key not valid for use in specified state" error
Original author: Alejandro Campos Magencio
Posting date: 2008-10-23T05:19:00+00:00


Hi all,

When executing RSACryptoServiceProvider.Encrypt method (see How to generate key pairs, encrypt and decrypt data with .NET (C#) for an example), you may get a System.Security.Cryptography.CryptographicException. According to MSDN, this is to be expected in several circumstances:

The cryptographic service provider (CSP) cannot be acquired. -or-

The length of the rgb parameter is greater than the maximum allowed length. -or-

The fOAEP parameter is true and OAEP padding is not supported.

 

In my case the error message of the exception was "Key not valid for use in specified state". Weird... Well, it took me a while to realize that this error message was certainly misleading! The key was just fine, the issue was that I was passing too many bytes to the Encrypt method! Check in MSDN the maximum length allowed by the different combinations of operating systems and padding.

I hope this helps.

Kind regards,

 

Alex (Alejandro Campos Magencio)


Share this article:

Comments:

Comments are closed.