RSA Encryption, getting bad length

Viewed 53590

When calling the following function :

byte[] bytes = rsa.Encrypt(System.Text.UTF8Encoding.UTF8.GetBytes(stringToEncrypt), true);

I am now getting the error: bad length.

With a smaller string it works, any ideas what the problem could be the string I am passing is under 200 characters.

4 Answers

I faced the same challenge while doing 2048 RSA encryption of plain text having less than 200 characters.

In my opinion, we can achieve the target without getting into complexity of Symmetric or Asymmetric encryption, with following simple steps;

By doing so I managed to encrypt and decrypt 40x larger text

Encryption:

  1. Compress the plain text by using *Zip() method and convert into array of bytes
  2. Encrypt with RSA

Decryption:

  1. Decrypt cypher text with RSA
  2. un-compress decrypted data by using **Unzip() method

*byte[] bytes = Zip(stringToEncrypt); // Zip() method copied below

**decryptedData = Unzip(decryptedBytes); // Unzip() method copied below


public static byte[] Zip(string str)
{
    var bytes = System.Text.Encoding.UTF8.GetBytes(str);    
    using (var msi = new MemoryStream(bytes))
    using (var mso = new MemoryStream())
    {
        using (var gs = new GZipStream(mso, CompressionMode.Compress))
        {                        
            CopyTo(msi, gs);
        }    
        return mso.ToArray();
    }
}
public static string Unzip(byte[] bytes)
{
    using (var msi = new MemoryStream(bytes))
    using (var mso = new MemoryStream())
    {
        using (var gs = new GZipStream(msi, CompressionMode.Decompress))
        {                     
            CopyTo(gs, mso);
        }    
        return System.Text.Encoding.UTF8.GetString(mso.ToArray());
    }
}

public static void CopyTo(Stream src, Stream dest)
    {
        byte[] bytes = new byte[4096];

        int cnt;

        while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0)
        {
            dest.Write(bytes, 0, cnt);
        }
    }
Related