RSA Algorithm - Not Decrypting! (C#)

Topics on common programming languages
User avatar
Trebor29
Lieutenant
Lieutenant
Posts: 75
Joined: Thu Apr 29, 2010 12:34 am

RSA Algorithm - Not Decrypting! (C#)

Post by Trebor29 » Thu Feb 02, 2012 4:26 am

Hi all,

I have been playing about with an RSA encryption / decryption application, trying to get my head round how it works as I will be wanting to implement it into an asp.net web payment application I am building for my dissertation.

I downloaded a simple Console example app. which works fine, and have been trying to reuse this code in a Windows Form Appication to simulate passing data from local > to server > and back... but for some reason I can not decrypt the encrypted text. When stepping through the code I can see that the 128 encryped data gets passed to the Decrypt() method, but for some reason it keeps jumping to the catch...! Any ideas?

Could it be because im making a new instance of the RSACryptoServiceProvider? Ive attachd both projects to make things easier... :biggrin:

Code: Select all

namespace encryptTut
{
    public sealed class RSAclass
    {
        internal static void RSADecrypt(byte[] encryptedData,RSAParameters rSAParameters,bool p)
        {
 	        try
            {
                byte[] decryptedData;

                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                {
                    RSA.ImportParameters(rSAParameters);

                    decryptedData = RSA.Decrypt(encryptedData, p);  //<<<<<<<< SKIPS TO CATCH HERE...?
                }
                Form2 serverFrm = new Form2();
                serverFrm.displayMsg(decryptedData);
            }
            catch (CryptographicException)
            {
                // ToDo:
            }
        }
    }
}
EncryptTut - Copy.zip
My app.
(52.38 KiB) Downloaded 590 times
User avatar
Trebor29
Lieutenant
Lieutenant
Posts: 75
Joined: Thu Apr 29, 2010 12:34 am

Re: RSA Algorithm - Not Decrypting! (C#)

Post by Trebor29 » Thu Feb 02, 2012 4:27 am

The Console App.....
RSA_consoleApp.zip
(27.02 KiB) Downloaded 626 times
User avatar
Saman
Lieutenant Colonel
Lieutenant Colonel
Posts: 828
Joined: Fri Jul 31, 2009 10:32 pm
Location: Mount Lavinia

Re: RSA Algorithm - Not Decrypting! (C#)

Post by Saman » Thu Feb 02, 2012 4:53 am

Compare with the following code and try to sort out yours.

Code: Select all

using System;
using System.Security.Cryptography;
using System.Text;

class RSACSPSample
{
    static void Main()
    {
        try
        {
            //Create a UnicodeEncoder to convert between byte array and string.
            ASCIIEncoding ByteConverter = new ASCIIEncoding();

            string dataString = "Data to Encrypt";

            //Create byte arrays to hold original, encrypted, and decrypted data.
            byte[] dataToEncrypt = ByteConverter.GetBytes(dataString);
            byte[] encryptedData;
            byte[] decryptedData;

            //Create a new instance of the RSACryptoServiceProvider class 
            // and automatically create a new key-pair.
            RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();

            //Display the origianl data to the console.
            Console.WriteLine("Original Data: {0}", dataString);

            //Encrypt the byte array and specify no OAEP padding.  
            //OAEP padding is only available on Microsoft Windows XP or
            //later.  
            encryptedData = RSAalg.Encrypt(dataToEncrypt, false);

            //Display the encrypted data to the console. 
            Console.WriteLine("Encrypted Data: {0}", ByteConverter.GetString(encryptedData));

            //Pass the data to ENCRYPT and boolean flag specifying 
            //no OAEP padding.
            decryptedData = RSAalg.Decrypt(encryptedData, false);

            //Display the decrypted plaintext to the console. 
            Console.WriteLine("Decrypted plaintext: {0}", ByteConverter.GetString(decryptedData));
        }
        catch(CryptographicException e)
        {
            //Catch this exception in case the encryption did
            //not succeed.
            Console.WriteLine(e.Message);

        }
    }
}
User avatar
Trebor29
Lieutenant
Lieutenant
Posts: 75
Joined: Thu Apr 29, 2010 12:34 am

Re: RSA Algorithm - Not Decrypting! (C#) Array cannot be null...

Post by Trebor29 » Thu Feb 02, 2012 7:44 pm

Hi Saman, Thanks for that..!

But unfortunately I still can't get mine to work. Your Console code is very similar to the one I downloaded, only with out the params and padding.

I still get the same error when using your code; "Array cannot be null"....

For some reason, even though the encrypted data is being passed, it fails to reverse it back into the Array!

If I use either code in one button_Click to display results in 2 textBoxes on same Form, this also works fine. It doesn't seam to like being passed anywhere...!

Does anyone know why the Array would be getting a null value..? :?

Thanks!
User avatar
Saman
Lieutenant Colonel
Lieutenant Colonel
Posts: 828
Joined: Fri Jul 31, 2009 10:32 pm
Location: Mount Lavinia

Re: RSA Algorithm - Not Decrypting! (C#)

Post by Saman » Thu Feb 02, 2012 11:55 pm

Looks like the string you pass to decrypt function isn't valid. Can you print those to screen before passing to function to see whether you pass what you need.
User avatar
Trebor29
Lieutenant
Lieutenant
Posts: 75
Joined: Thu Apr 29, 2010 12:34 am

Re: RSA Algorithm - Not Decrypting! (C#)

Post by Trebor29 » Fri Feb 03, 2012 12:21 am

Ye I think so...

I can encrypt a string message in Form1 and send it over to Form2, I know the encrypted data gets received in Form2 because I can see the value of (128), which im guessing would be the bit encryption... And I can display the encrypted data in a textBox on Form2.

But as soon as I step over the RSAalg.Decrypt() method, (128) becomes - null...! Im stumped! :shock:

If I do the same thing but on one Form, and display the decrypted message in textBox2, it works....

Its a tricky one :?:

I'll attach the latest version, bit simpler I think... Cant remember which version I uploaded!
EncryptTut - Copy - Copy - Copy.zip
(64.6 KiB) Downloaded 563 times
User avatar
Saman
Lieutenant Colonel
Lieutenant Colonel
Posts: 828
Joined: Fri Jul 31, 2009 10:32 pm
Location: Mount Lavinia

Re: RSA Algorithm - Not Decrypting! (C#)

Post by Saman » Fri Feb 03, 2012 12:33 am

Now the problem has become far more simpler to sort out. It is likely that you have defined a variable in a private scope which became invalid when you pass it to another scope. Just make those passing variable public/global and see what you get.
User avatar
Trebor29
Lieutenant
Lieutenant
Posts: 75
Joined: Thu Apr 29, 2010 12:34 am

Re: RSA Algorithm - Not Decrypting! (C#)

Post by Trebor29 » Fri Feb 03, 2012 2:05 am

No... :cry:

Ive set everything to public and all variables are set global. It keeps jumping into the 'catch' (button2_Click() / Form1) and still getting the null value.

If I comment out the try / catch, the program falls over at the RSAalg.Decrypt() method with;

"CryptographicException was unhandled" (Bad Data)

It seems like the data is being changed somehow when it is passed from Form1 to Form2... :?:
User avatar
Saman
Lieutenant Colonel
Lieutenant Colonel
Posts: 828
Joined: Fri Jul 31, 2009 10:32 pm
Location: Mount Lavinia

Re: RSA Algorithm - Not Decrypting! (C#)

Post by Saman » Fri Feb 03, 2012 2:48 am

I had to run your code to find the problem. Next time I'll only do that at a cost :)
The reason is you use two RSA objects, one defined at Form1 and the other at Form2.

Do these mods to get it running...
  1. Find private void button2_Click(object sender, EventArgs e) in Form1
  2. Now find frm2.displayMsg(encryptedData);
  3. Replace that line with frm2.displayMsg(encryptedData, RSAalg);
  4. Find RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider(); in Form2
  5. Comment that out
  6. Find byte[] encryptedData; and replace with byte[] encryptedData1;
  7. Find public void displayMsg(byte[] encryptedData) and replace with public void displayMsg(byte[] encryptedData, RSACryptoServiceProvider RSAalg)
  8. Find textBox1.Text = ("Encrypted Message: " + ByteConverter.GetString(encryptedData)); and replace with textBox1.Text = ("Encrypted Message: " + ByteConverter.GetString(encryptedData1));
Now type something on Form1, click encrypt and then on send. When you are in Form2, click on Decrypt. You'll get the original text.

Good luck!
User avatar
Trebor29
Lieutenant
Lieutenant
Posts: 75
Joined: Thu Apr 29, 2010 12:34 am

Re: RSA Algorithm - Not Decrypting! (C#)

Post by Trebor29 » Fri Feb 03, 2012 3:55 am

Well well well... :D I cant thank you enough for getting rid of that headache... :biggrin:

Ive only just started to look at encryption / decryption 2 days ago, so im still trying to work this out in my head.

So have I got this right;....

An RSACryptoServiceProvider object creates one set key pairs? so I was effectivly creating two key pairs... yes?

With 1 RSACSP object created, sending it with the encrypted data... is that basicly sending the corresponding key to decrypt the data? Is that right?

It doesn't sound right, because to send the decryption key with the message :? isn't very secure... although this is a very basic application. Could this be split up, so that the relevant key was sent separate from the encrypted data?

Also, how do you know which is the public and private key? Is it the initial encrypted message (origin) has the public key and the intended destination / recipient of the data has the private key?

Sorry for all these question Saman, but I need to understand..! :geek:

Thanks again.
Post Reply

Return to “.Net & Other Programming”