Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Bad Data" CryptographicException

First, I have only written the code below for academic purposes. The reason I say this is because I am not putting this in a production environment, and therefor am "bypassing" some of the overhead that I would need to do if I was, I simply need to be able to encrypt/decrypt a string using the code below. I was able to do it a few time, but for some reason, I started receiving "CryptographicException Bad Data" and am not sure what might be causing the problem.

   private string RSAEncrypt(string value)
    {
        byte[] encryptedData = Encoding.Unicode.GetBytes(value);

        CspParameters cspParams = new CspParameters();
        cspParams.KeyContainerName = _rsaContainerName;
        using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(2048,cspParams))
        {
            encryptedData = RSA.Encrypt(encryptedData, false);
            return Convert.ToBase64String(encryptedData);

        }

    }



    private string RSADecrypt(string value)
    {

        byte[] encryptedData = Encoding.Unicode.GetBytes(value);

        CspParameters cspParams = new CspParameters();
        cspParams.KeyContainerName = _rsaContainerName;
        using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(2048,cspParams))
        { 
            encryptedData = RSA.Decrypt(encryptedData,false);
            return Convert.ToBase64String(encryptedData);

        }
    }

It is only throwing this exception on the RSADecrypt call.

Any ideas? I read somewhere it might have to do with the expected size of encryptedData that is passed into RSA.Decrypt.

Thanks }

like image 324
TheJediCowboy Avatar asked Mar 11 '12 23:03

TheJediCowboy


1 Answers

  • Convert the plaintext back and forth using a string-encoding (i.e. Encoding.Unicode).

  • Convert the encrypted data back and forth using Base-64 (i.e. Convert.[To/From]Base64String);

Like this:

private string RSAEncrypt(string value)
{
    byte[] plaintext = Encoding.Unicode.GetBytes(value);

    CspParameters cspParams = new CspParameters();
    cspParams.KeyContainerName = _rsaContainerName;
    using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(2048,cspParams))
    {
        byte[] encryptedData = RSA.Encrypt(plaintext, false);
        return Convert.ToBase64String(encryptedData);
    }
}

private string RSADecrypt(string value)
{
    byte[] encryptedData = Convert.FromBase64String(value);

    CspParameters cspParams = new CspParameters();
    cspParams.KeyContainerName = _rsaContainerName;
    using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(2048,cspParams))
    { 
        byte[] decryptedData = RSA.Decrypt(encryptedData,false);
        return Encoding.Unicode.GetString(decryptedData);
    }
}
like image 158
Rasmus Faber Avatar answered Oct 22 '22 16:10

Rasmus Faber