7

I'm quite new to all this encryption thing and I'm trying to do a simple app to encrypt a given string. Here's my code:

public static X509Certificate2 getPublicKey()
{
    RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

    X509Certificate2 cert2 = new X509Certificate2("c:\\certificate.cer");

    return cert2;
}


public static string cipherRequest(byte[] stringToEncrypt)
{
    X509Certificate2 certificate = getPublicKey();

    RSACryptoServiceProvider rsa = certificate.PublicKey.Key as RSACryptoServiceProvider;

    byte[] cryptedData = rsa.Encrypt(stringToEncrypt, true);

    return Convert.ToBase64String(cryptedData);
}

public static void Main()
{

    try
    {

        ASCIIEncoding ByteConverter = new ASCIIEncoding();

        byte[] test = ByteConverter.GetBytes("stringtoencrypt");

        string first = cipherRequest(test);
        string second= cipherRequest(test);

        Console.WriteLine("first: {0}", first);
        Console.WriteLine("second: {0}", second);

    }
    catch(CryptographicException e)
    {
        Console.WriteLine(e.Message);
    }

}

So every time I call the cipherRequest it produces different results. I've checked the certificate is loaded but it produces different results.

Any thoughts?

2
  • 3
    This behavior is by design. Is there an actual problem?
    – SLaks
    Dec 6, 2012 at 18:05
  • 1
    Why do you have a byte[] named string?
    – SLaks
    Dec 6, 2012 at 18:09

1 Answer 1

7

Random padding is added before the actual encryption to avoid certain attacks. This is why you are getting different results each time you call the encryption method.

For more info, see this post:

RSA in C# does not produce same encrypted string for specific keys?

1
  • Thanks, through some more reading i've managed to reach that conclusion :) My bad
    – antistes
    Dec 7, 2012 at 9:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.