Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / .NET Framework / CLR / June 2004

Tip: Looking for answers? Try searching our database.

Help wanted on cryptography decryption..Urgent

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Venkatesa - 16 Jun 2004 21:34 GMT
Hi Everyone,
       I am facing a problem while decrypting a stream object using
.NET cryptographic classes.Below i have pasted the code i used to
encrypt and decrypt a stream object.The encryption seems to work fine,
but the decryptiion fails with an error "Bad data".I am really not
able to figure out what the proble is and would really apperciate if
someone can help me.
Thanks a lot.

Code to encrypt a stream

sourceStream parameter is just a empty memory stream.
**************************************************************************
public CryptoStream EncryptStream(Stream sourceStream,string
key,string initializationVector)
        {
            //Create ICryptoTransform and get the encryptor of the service
provider.Convert the key and IV to byte array.
           
            ICryptoTransform encryptTransform  =
_cryptoserviceprovider.CreateEncryptor(
                                                        UTF8Encoding.UTF8.GetBytes(key),
                                                        UTF8Encoding.UTF8.GetBytes(initializationVector));
            CryptoStream cryptStream  = null;
            try
            {
                cryptStream = new
CryptoStream(sourceStream,encryptTransform,CryptoStreamMode.Write);
            }
            finally
            {
                //if(cryptStream != null)
                    //cryptStream.Close();
               
            }
            return cryptStream;

        }

***************************************************************************

Code to encrypt a stream

sourceStream parameter is memory stream containing the encrypted
stream.

    public CryptoStream DecryptStream(Stream sourceStream,string
key,string initializationVector)
        {
            ICryptoTransform decryptTransform =
_cryptoserviceprovider.CreateDecryptor(
                                                        UTF8Encoding.UTF8.GetBytes(key),
                                                        UTF8Encoding.UTF8.GetBytes(initializationVector));
            CryptoStream cryptStream  = null;
            try
            {
                cryptStream = new
CryptoStream(sourceStream,decryptTransform,CryptoStreamMode.Read);

                //some more logic to actually decrypt
            }
            catch(Exception ex)
            {
                string ge = ex.Message.ToString();
                MessageBox.Show(ex.Message);  
            }
            finally
            {
                //if(cryptStream != null)
                //    cryptStream.Close();
            }
            return cryptStream;
        }

When i look for the value in the returned cryptoStream ,there seems to
be no data in it.

The code breaks when i use a streamreader obect to read the
cryptostream using stream reader object to read the string in it .i.e.

StreamReader SReader2 = new StreamReader( cryptStream);
            MessageBox.Show(SReader2.ReadToEnd());

and i recdeive the error message "Bad Data".

Can anyone please help me ?

Thanks
Jon Skeet [C# MVP] - 16 Jun 2004 22:29 GMT
>         I am facing a problem while decrypting a stream object using
> .NET cryptographic classes.Below i have pasted the code i used to
> encrypt and decrypt a stream object.The encryption seems to work fine,
> but the decryptiion fails with an error "Bad data".I am really not
> able to figure out what the proble is and would really apperciate if
> someone can help me.

You haven't shown the code where you're using the stream you're
returning.

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

I'm sure once we can see all your code (or rather, the relevant code)
the problem will become fairly obvious.

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

.NET Developer - 16 Jun 2004 23:38 GMT
Hi everybody,
  I apologize for sending large undescriptive code.

Here is the clear explanation.

I am trying to ecrypt/decrypt  a stream object and return a stream
object to the calling function.

The encrypt function is as follows.


public CryptoStream EncryptStream(Stream sourceStream,string
key,string initializationVector)
       {
           //Create ICryptoTransform and get the encryptor of the
service
provider.Convert the key and IV to byte array.
           
           ICryptoTransform encryptTransform =
_cryptoserviceprovider.CreateEncryptor(

UTF8Encoding.UTF8.GetBytes(key),

UTF8Encoding.UTF8.GetBytes(initializationVector));
           CryptoStream cryptStream = null;
           try
           {
               cryptStream = new
CryptoStream(sourceStream,encryptTransform,CryptoStreamMode.Write);
           }
           finally
           {
               //if(cryptStream != null)
                   //cryptStream.Close();
               
           }
           return cryptStream;

       }

This code is invoked as follows.

MemoryStream ms = new System.IO.MemoryStream()
CryptoStream es  = EncryptStream(ms,key,IV);

I am passing a MemoryStream object to the function which returns a
CryptoStream.

Then i write to the CryptoStream as follows.

StreamWriter strwtr = new StreamWriter(es);
strwtr.Write("Some text to be encrypted");

Now when i read the underlying memorystream in the cryptostream i get
some encrypted text.

StreamReader strrdr1 = new StreamReader(ms);
MessageBox.Show(strrdr1.ReadToEnd());

The code to encrypt data works fine but when i send the encrypted stream
to be decrypted i am unable to reproduce the original text.

Code to decrypt:

   public CryptoStream DecryptStream(Stream sourceStream,string
key,string initializationVector)
       {
           ICryptoTransform decryptTransform =
_cryptoserviceprovider.CreateDecryptor(

UTF8Encoding.UTF8.GetBytes(key),

UTF8Encoding.UTF8.GetBytes(initializationVector));
           CryptoStream cryptStream = null;
           try
           {
               cryptStream = new
CryptoStream(sourceStream,decryptTransform,CryptoStreamMode.Read);

               //some more logic to actually decrypt
           }
           catch(Exception ex)
           {
               string ge = ex.Message.ToString();
               MessageBox.Show(ex.Message);  
           }
           finally
           {
               if(cryptStream != null)
                   cryptStream.Close();
           }
           return cryptStream;
       }

I invoke the above function as follows.

CryptoStream decryptedResult = DecryptStream(ms,key,IV);

that is, i pass the the encrypted memory stream object (returned by
Encrypt function) in the "sourceStream" parameter of the Decrypt
function. I then return the cryptostream.

when i try to read the returned cryptostream object i get "Bad Data"
error.

I read the cryptostream as follows.

StreamReader strrdr2 = new StreamReader(decryptedResult);
MessageBox.Show(strrdr2.ReadToEnd());

I get error ("Bad Data") when the last line is executed.
When i saw the contents of decryptedResult, it was empty.
That is the stream was not decrypted.

Hope this helps.
Please let me know if u need more explanation.

I will really apperciate a early response.

Thanks a lot!
Jon Skeet [C# MVP] - 17 Jun 2004 08:12 GMT
>    I apologize for sending large undescriptive code.
> Here is the clear explanation.

<snip>

I've sent a private email about this, but here's the basic rundown:

o Reading from the MemoryStream without resetting the position will
 give no data.
o If the CryptoStream is closed, the MemoryStream will be too.
o Not flushing the final block will lead to bad data.
o Treating the encrypted data as if it were UTF-8 encoded text will
 lead to corruption.

*Complete* code would, as ever, be much more useful. A sample program
which can be tweaked until it works is easier to work with.

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

.NET Developer - 17 Jun 2004 17:42 GMT
Hi Jon,
     Thanks a lot for ur quick and explanatory reply.
Using FlushFinalBalock on the decrypted stream helped me
in getting rid of "Bad Data" error, but i am still not able to decrypt a
memorystream.

I have n no problem in encrypting a Memorystream, but i am not able to
decrypt the memorystream. The code for decrypting memorystream is as
follows

"sourceStream" parameter has encrypted MemoryStream object

public Stream DecryptStream(Stream sourceStream,string key,string
initializationVector)
        {
            ICryptoTransform decryptTransform =
_cryptoserviceprovider.CreateDecryptor(
                                                        UTF8Encoding.UTF8.GetBytes(key),
                                                        UTF8Encoding.UTF8.GetBytes(initializationVector));
                       
            CryptoStream cryptStream  = null;
            try
            {
                cryptStream = new
CryptoStream(sourceStream,decryptTransform,CryptoStreamMode.Read);
                cryptStream.FlushFinalBlock();
               
            }
            catch(Exception ex)
            {
                string ge = ex.Message.ToString();
                MessageBox.Show(ex.Message);  
            }
       
        return cryptStream;
}

When i read the cryptStream i see nothing in it. Is there anything
basically wrong in my code?
Can i not decrypt a Memorystream using CryptoStream?

It wud be really great if u can help me on this problem.

Once again thanks a lot!
Tarik Soulami - 24 Jun 2004 20:06 GMT
The following MSDN article shows some sample code of how to do encryption/decryption using CryptoStream over a NetworkStream but you could do the
same with MemoryStream or FileStream, etc...
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cp
conencryptingdata.asp


Thanks,
--Tarik

--------------------
>From:     .NET Developer <balsoo_99@yahoo.com>
>References: <MPG.1b3b54ace043524198acaa@msnews.microsoft.com>
[quoted text clipped - 31 lines]
>                                                        UTF8Encoding.UTF8.GetBytes(key),
>                                                        UTF8Encoding.UTF8.GetBytes
(initializationVector));
>                       
>            CryptoStream cryptStream  = null;
[quoted text clipped - 24 lines]
>*** Sent via Devdex http://www.devdex.com ***
>Don't just participate in USENET...get rewarded for it!

Rate this thread:







Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.