System.Security.Cryptography.CryptographicException : Bad length in RSACryptoserviceProvider

c#, encryption, rsa, windows-phone-8

Solution

RSA is only meant to be used for encrypting small amounts of data. The exact amount you can encrypt depends on the key length + the amount used by the padding. A 1024 bit key would allow for a bit above 100 bytes.

Since RSA is quite slow, the usual way to encrypt large messages is using hybrid encryption. In hybrid encryption you use a fast symmetric encryption algorithm (like AES) for encrypting the data with a random key. The random key is then encrypted with RSA and send along with the symmetric key encrypted data.

Problem

I want encrypt and decrypt data using `RSACryptoServiceProvider` in c# in wp8 project. I am creating asymmetric keys as : ``` CspParameters parameters = new CspParameters(); parameters.KeyContainerName = "MyContainer"; RSACryptoServiceProvider provider = new RSACryptoServiceProvider(parameters); ``` Now I want do encrypt data. I am doing: ``` CspParameters parameters = new CspParameters(); parameters.KeyContainerName = "MyContainer"; RSACryptoServiceProvider obj = new RSACryptoServiceProvider(parameters); byte[] a = Generic.RSAEncrypt(ByteConverter.GetBytes(s[0]), obj.ExportParameters(false), false); public static byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding) { try { byte[] encryptedData; //Create a new instance of RSACryptoServiceProvider. CspParameters parameters = new CspParameters(); parameters.KeyContainerName = "TCSContainer"; using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(parameters)) { //Import the RSA Key information. This only needs //to include the public key information. RSA.ImportParameters(RSAKeyInfo); //Encrypt the passed byte array and specify OAEP padding. //OAEP padding is only available on Microsoft Windows XP or //later. encryptedData = RSA.Encrypt(DataToEncrypt, DoOAEPPadding); } return encryptedData; } catch (CryptographicException e) { //Catch and display a CryptographicException //to the console. //Console.WriteLine(e.Message); return null; } } ``` Now I am getting exception while encypting: ``` RSA.EncryptSystem.Security.Cryptography.CryptographicException : Bad length in RSACryptoserviceProvider. ``` Stacktrace is: ``` at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) at System.Security.Cryptography.RSACryptoServiceProvider.EncryptKey(SafeKeyHandle pKeyContext, Byte[] pbKey, Int32 cbKey, Boolean fOAEP, ObjectHandleOnStack ohRetEncryptedKey) at System.Security.Cryptography.RSACryptoServiceProvider.Encrypt(Byte[] rgb, Boolean fOAEP) at WindowsAppmart.Generic.RSAEncrypt(Byte[] DataToEncrypt, RSAParameters RSAKeyInfo, Boolean DoOAEPPadding) ``` and message is Bad Length. I am not getting where can I go wrong?

Original source

Related problems