troubleshooting Question

RSACryptoServiceProvider to decrypt with a public key

Avatar of Solveweb
Solveweb asked on
1 Comment1 Solution3451 ViewsLast Modified:
I can not get RSACryptoServiceProvider to work at all. Help! Can someone please tell me why when incudePrivateKeyInfo is false, the code below reports the error "Key not valid for use in specified state.", but when incudePrivateKeyInfo is true it reports "Unspecified Error". If my assumprtions are correct, the code below should be able to encrypt a string using RSA with eauther the rivcate key or the public key, but I can do neither.


        private string rsaEncrypt(string plainText, RSAParameters rsaParam)

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] byteInput = (new UTF8Encoding()).GetBytes(plainText);
            byte[] byteEncrypted = rsa.Encrypt(byteInput, false);
            string encyrptedText = (new UTF8Encoding()).GetString(byteEncrypted);
            return encyrptedText;


        private string rsaDecrypt(string cipherText, RSAParameters rsaParam)

            CspParameters CSPParam = new CspParameters();
            CSPParam.Flags = CspProviderFlags.UseExistingKey;
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(CSPParam);
            byte[] byteEncryptedString = (new UTF8Encoding()).GetBytes(cipherText);
            byte[] byteDecryptedString = rsa.Decrypt(byteEncryptedString, false);
            return (new UTF8Encoding()).GetString(byteDecryptedString);

        private RSAParameters rsaGenerateKey(bool includePrivate)
            CspParameters CSPParam = new CspParameters();
            CSPParam.Flags = CspProviderFlags.UseMachineKeyStore;
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(CSPParam);
            RSAParameters rsaParam = rsa.ExportParameters(includePrivate);
            return rsaParam;

        public void main()
            string input = "encrypt me please";
            bool incudePrivateKeyInfo = false;
            RSAParameters rsaParam = CryptoHelper.rsaGenerateKey(incudePrivateKeyInfo);
            string output = CryptoHelper.rsaEncrypt(newBuffer, rsaParam);

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 1 Comment.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 1 Comment.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros