Link to home
Start Free TrialLog in
Avatar of Solveweb
Solveweb

asked on

RSACryptoServiceProvider to decrypt with a public key

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.

Thanks

        private string rsaEncrypt(string plainText, RSAParameters rsaParam)
        {

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.ImportParameters(rsaParam);
            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);
            rsa.ImportParameters(rsaParam);
            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);
        }
ASKER CERTIFIED SOLUTION
Avatar of joechina
joechina

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial