473,388 Members | 1,400 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

CryptoStream?

Hi,

I want to use DES and CryptoStream to serialize a encrypted stream to a file
with a header "CRYPT". And I wrote these code:

To store:

FileStream fileStream = new FileStream(fileName, FileMode.Create,
FileAccess.Write, FileShare.None);
byte[] signture = AE.GetBytes("CRYPT");
fileStream.Write(signture, 0, 5);

ICryptoTransform ct = des.CreateDecryptor(key, iv);
CryptoStream cryptoStream = new CryptoStream(fileStream, ct,
CryptoStreamMode.Write);

IFormatter formatter = new BinaryFormatter();
formatter.Binder = new DataSNBinder();
formatter.Serialize(cryptoStream, MYDATA);

cryptoStream.Flush();
fileStream.Close();

To load:

FileStream fileStream = new FileStream(fileName, FileMode.Open,
FileAccess.Read);
fileStream.Seek(5, SeekOrigin.Begin);
ICryptoTransform ct = des.CreateDecryptor(key, iv);
CryptoStream cryptoStream = new CryptoStream(fileStream, ct,
CryptoStreamMode.Read);
formatter = new BinaryFormatter();
formatter.Binder = new DataSNBinder();
MYDATA = (MYDATA)formatter.Deserialize(cryptoStream);
cryptoStream.Close();

And with that code I can not load the saved file. What's the problem?

And, what's the exact meaning of CryptoStream.Close()? If I replace the
CryptoStream.Flush() with Close(), it will crash. But the encrypted file
size is somewhat smaller than the original data size, is that mean a problem
in my code?

Thank you very much
weixiang
Nov 15 '05 #1
5 12900
Thank you. I'll test that ASAP.

What's the CryptoStream.Close() mean? It will throw a exception if I use
that to instead CryptoStream.Flush()

"Rob Teixeira [MVP]" <RobTeixeira@@msn.com> wrote in message
news:uk**************@TK2MSFTNGP10.phx.gbl...
I haven't run the code, but I immediately noticed something that needs to
get fixed.
After the last write into the CrypoStream, you MUST call FlushFinalBlock
(not Flush).
The final block of cypher data must be properly padded according to the
cypher, otherwise, you can't decrypt.

-Rob [MVP]

"weixiang" <we******@yahoo.com> wrote in message
news:#C**************@tk2msftngp13.phx.gbl...
Hi,

I want to use DES and CryptoStream to serialize a encrypted stream to a

file
with a header "CRYPT". And I wrote these code:

To store:

FileStream fileStream = new FileStream(fileName, FileMode.Create,
FileAccess.Write, FileShare.None);
byte[] signture = AE.GetBytes("CRYPT");
fileStream.Write(signture, 0, 5);

ICryptoTransform ct = des.CreateDecryptor(key, iv);
CryptoStream cryptoStream = new CryptoStream(fileStream, ct,
CryptoStreamMode.Write);

IFormatter formatter = new BinaryFormatter();
formatter.Binder = new DataSNBinder();
formatter.Serialize(cryptoStream, MYDATA);

cryptoStream.Flush();
fileStream.Close();

To load:

FileStream fileStream = new FileStream(fileName, FileMode.Open,
FileAccess.Read);
fileStream.Seek(5, SeekOrigin.Begin);
ICryptoTransform ct = des.CreateDecryptor(key, iv);
CryptoStream cryptoStream = new CryptoStream(fileStream, ct,
CryptoStreamMode.Read);
formatter = new BinaryFormatter();
formatter.Binder = new DataSNBinder();
MYDATA = (MYDATA)formatter.Deserialize(cryptoStream);
cryptoStream.Close();

And with that code I can not load the saved file. What's the problem?

And, what's the exact meaning of CryptoStream.Close()? If I replace the
CryptoStream.Flush() with Close(), it will crash. But the encrypted file size is somewhat smaller than the original data size, is that mean a

problem
in my code?

Thank you very much
weixiang


Nov 15 '05 #2
Close will close the CryptoStream and the underlying stream object the
CryptoStream is writing to.
In accordance to stream behavior, Close calls Flush, but in this case, you
need to call FlushFinalBlock.

-Rob [MVP]

"weixiang" <we******@yahoo.com> wrote in message
news:eb**************@TK2MSFTNGP12.phx.gbl...
Thank you. I'll test that ASAP.

What's the CryptoStream.Close() mean? It will throw a exception if I use
that to instead CryptoStream.Flush()

"Rob Teixeira [MVP]" <RobTeixeira@@msn.com> wrote in message
news:uk**************@TK2MSFTNGP10.phx.gbl...
I haven't run the code, but I immediately noticed something that needs to
get fixed.
After the last write into the CrypoStream, you MUST call FlushFinalBlock
(not Flush).
The final block of cypher data must be properly padded according to the
cypher, otherwise, you can't decrypt.

-Rob [MVP]

"weixiang" <we******@yahoo.com> wrote in message
news:#C**************@tk2msftngp13.phx.gbl...
Hi,

I want to use DES and CryptoStream to serialize a encrypted stream to a
file
with a header "CRYPT". And I wrote these code:

To store:

FileStream fileStream = new FileStream(fileName, FileMode.Create,
FileAccess.Write, FileShare.None);
byte[] signture = AE.GetBytes("CRYPT");
fileStream.Write(signture, 0, 5);

ICryptoTransform ct = des.CreateDecryptor(key, iv);
CryptoStream cryptoStream = new CryptoStream(fileStream, ct,
CryptoStreamMode.Write);

IFormatter formatter = new BinaryFormatter();
formatter.Binder = new DataSNBinder();
formatter.Serialize(cryptoStream, MYDATA);

cryptoStream.Flush();
fileStream.Close();

To load:

FileStream fileStream = new FileStream(fileName, FileMode.Open,
FileAccess.Read);
fileStream.Seek(5, SeekOrigin.Begin);
ICryptoTransform ct = des.CreateDecryptor(key, iv);
CryptoStream cryptoStream = new CryptoStream(fileStream, ct,
CryptoStreamMode.Read);
formatter = new BinaryFormatter();
formatter.Binder = new DataSNBinder();
MYDATA = (MYDATA)formatter.Deserialize(cryptoStream);
cryptoStream.Close();

And with that code I can not load the saved file. What's the problem?

And, what's the exact meaning of CryptoStream.Close()? If I replace

the CryptoStream.Flush() with Close(), it will crash. But the encrypted

file size is somewhat smaller than the original data size, is that mean a

problem
in my code?

Thank you very much
weixiang



Nov 15 '05 #3
So why doesn't Close call FlushFinalBlock? Why would you ever not want it
to?

S.

"Rob Teixeira [MVP]" <RobTeixeira@@msn.com> wrote in message
news:uU**************@TK2MSFTNGP11.phx.gbl...
Close will close the CryptoStream and the underlying stream object the
CryptoStream is writing to.
In accordance to stream behavior, Close calls Flush, but in this case, you
need to call FlushFinalBlock.

-Rob [MVP]


Nov 15 '05 #4
I tried to call FlushFinalBlock to instead Flush, but it still throw a
exception that said "Length of the data to decrypt is invalid". Is there
other problem? And I believe I am going to encrypt my data, not to decrypt
it. Is that declared in the CryptoStream constructor with CSMode.Write?

Here is my current code:

FileStream fileStream = new FileStream(fileName, FileMode.Create,
FileAccess.Write, FileShare.None);
byte[] signture = AE.GetBytes("CRYPT");
fileStream.Write(signture, 0, 5);

ICryptoTransform ct = des.CreateDecryptor(key, iv);
CryptoStream cryptoStream = new CryptoStream(fileStream, ct,
CryptoStreamMode.Write);

IFormatter formatter = new BinaryFormatter();
formatter.Binder = new DataSNBinder();
formatter.Serialize(cryptoStream, MYDATA);

cryptoStream.FlushFinalBlock(); // throw exception here
fileStream.Close();
"Simon Trew" <ten.egnaro@werts> wrote in message
news:%2******************@TK2MSFTNGP10.phx.gbl...
So why doesn't Close call FlushFinalBlock? Why would you ever not want it
to?

S.

"Rob Teixeira [MVP]" <RobTeixeira@@msn.com> wrote in message
news:uU**************@TK2MSFTNGP11.phx.gbl...
Close will close the CryptoStream and the underlying stream object the
CryptoStream is writing to.
In accordance to stream behavior, Close calls Flush, but in this case, you need to call FlushFinalBlock.

-Rob [MVP]


Nov 15 '05 #5
OK, instead of trying to wade through the code, I wrote my own ;-)
This sample includes just about everything you need. I'm serializing a
string object, but that could easily be any object.

byte[] key = new byte[8];

byte[] iv = new byte[8];

FileStream fs = null;

CryptoStream cs = null;

BinaryFormatter bf = null;

string myData = "This is some test data.";

string myData2 = string.Empty;

DES desCypher = DES.Create();

// Encryption starts here

try

{

// create some key and IV data for the sample

RandomNumberGenerator.Create().GetBytes(key);

RandomNumberGenerator.Create().GetBytes(iv);

fs = new FileStream(@"C:\sample.dat", FileMode.OpenOrCreate);

fs.Write(Encoding.ASCII.GetBytes("CRYPT"), 0, 5);

cs = new CryptoStream(fs, desCypher.CreateEncryptor(key, iv),
CryptoStreamMode.Write);

bf = new BinaryFormatter();

bf.Serialize(cs, myData);

cs.FlushFinalBlock();

}

catch (Exception ex)

{

MessageBox.Show(ex.ToString());

}

finally

{

if (cs != null) cs.Close();

}

// decryption starts here

try

{

fs = new FileStream(@"C:\sample.dat", FileMode.Open);

fs.Position = 5;

cs = new CryptoStream(fs, desCypher.CreateDecryptor(key, iv),
CryptoStreamMode.Read);

myData2 = bf.Deserialize(cs) as string;

MessageBox.Show(myData2);

}

catch (Exception ex)

{

MessageBox.Show(ex.ToString());

}

finally

{

if (cs != null) cs.Close();

}

-Rob [MVP]
"weixiang" <we******@yahoo.com> wrote in message
news:u1**************@TK2MSFTNGP09.phx.gbl...
I tried to call FlushFinalBlock to instead Flush, but it still throw a
exception that said "Length of the data to decrypt is invalid". Is there
other problem? And I believe I am going to encrypt my data, not to decrypt it. Is that declared in the CryptoStream constructor with CSMode.Write?

Here is my current code:

FileStream fileStream = new FileStream(fileName, FileMode.Create,
FileAccess.Write, FileShare.None);
byte[] signture = AE.GetBytes("CRYPT");
fileStream.Write(signture, 0, 5);

ICryptoTransform ct = des.CreateDecryptor(key, iv);
CryptoStream cryptoStream = new CryptoStream(fileStream, ct,
CryptoStreamMode.Write);

IFormatter formatter = new BinaryFormatter();
formatter.Binder = new DataSNBinder();
formatter.Serialize(cryptoStream, MYDATA);

cryptoStream.FlushFinalBlock(); // throw exception here
fileStream.Close();
"Simon Trew" <ten.egnaro@werts> wrote in message
news:%2******************@TK2MSFTNGP10.phx.gbl...
So why doesn't Close call FlushFinalBlock? Why would you ever not want it
to?

S.

"Rob Teixeira [MVP]" <RobTeixeira@@msn.com> wrote in message
news:uU**************@TK2MSFTNGP11.phx.gbl...
Close will close the CryptoStream and the underlying stream object the
CryptoStream is writing to.
In accordance to stream behavior, Close calls Flush, but in this case,

you need to call FlushFinalBlock.

-Rob [MVP]



Nov 15 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Stingray | last post by:
Are there any know problems with using a MemoryStream as a backing store for a CryptoStream? I'm trying to simply encrypt and decrypt text in memory. I'd like to create some simple methods to...
2
by: Ayende Rahien | last post by:
I've a problem in my code using NetworkStream. I've a server which listen to a port, and then Read() from it, and a client that send data. My NetworkStream is wrapped in a CryptoStream, and my...
8
by: MattP | last post by:
Ok, with the help of some examples found on the web and some minor modifications on our own, we have a simple and working encrypt and decrypt solution. It runs as a service, watches for files with...
0
by: Daniel Weber | last post by:
Hi! In my code I create a CryptoStream around another stream of my own, with CryptoStreamMode.Read. So I just can read from the CryptoStream. When I close that CryptoStream, however, the...
2
by: pesso | last post by:
I have the following code that's taken and modified from a got_dot_net example. I'm trying to decrypt an Xml file that's been encrypted. I can dump the decrypted stream to the console, but if I...
7
by: semedao | last post by:
Hi, I am using cryptostream on both sides on tcp connection that pass data. I am also use asyc socket , so , the data that recieved in the callback method not always have the length of the buffer...
9
by: TC | last post by:
Hey All, I posted this to the Crypto users group and forgot to add the VB.Net users group. I apologize for any confusion. I have been testing a try / catch / finally block and purposely...
2
by: =?Utf-8?B?TWFydGluIE1hZHJlemE=?= | last post by:
Hi, i've got problems with CryptoStream and GZipStream. Someone tried that? Or got any idea why this wont work? i tried every combination, first i used CryptoStream, after that GZipStream. Or...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.