Simple file encryption decryption problem in C#

A

Andrew Jocelyn

Hi

I've created an encrypt and decrypt function, modified from article
http://www.dotnetthis.com/Articles/Crypto.htm. It accepts streams instead of
file paths. The functions work if I send in FileStreams. I can encrypt and
decrypt. If I send in a MemoryStream to it then write the stream to the
website response stream the stream seems to be truncated. It needs to work
with all file types. It breaks even with a short text file.

Code below. What am I doing wrong?

using (var fileStream = new FileStream(fileName, FileMode.Open,
FileAccess.Read))
{
var ms = new MemoryStream();
Cryptography.Decrypt(fileStream, ms, "password");

byte[] prescan = ms.ToArray();
ms.Close();

Response.Clear();
Response.ContentType = ContentType;
Response.OutputStream.Write(prescan, 0, prescan.Length);
Response.End();

}

// decrypt function

public static void Decrypt(Stream fsIn,
Stream fsOut, string Password)
{
var pdb = new Rfc2898DeriveBytes(Password,
new byte[]
{
0x49, 0x76, 0x61, 0x6e,
0x20, 0x4d,
0x65, 0x64, 0x76, 0x65,
0x64, 0x65, 0x76
});

TripleDES alg = TripleDES.Create();
alg.Key = pdb.GetBytes(16);
alg.IV = pdb.GetBytes(8);

var cs = new CryptoStream(fsOut, alg.CreateDecryptor(),
CryptoStreamMode.Write);

const int bufferLen = 4096;
var buffer = new byte[bufferLen];
int bytesRead;

do
{
bytesRead = fsIn.Read(buffer, 0, bufferLen);
cs.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);

//cs.Close(); // commented out to stop output steam being closed
before it's used
fsIn.Close();
}

Many thanks
Andrew
 
J

Jie Wang [MSFT]

Hi Andrew,

As Peter and rossum mentioned, you need to flush the crypto stream or call
Close on it before all the data will be processed.

To flush the crypto stream, you can call FlushFinalBlock on it instead of
Flush.

Here is the code I've made some changes based on your initial code:

public static void Encrypt(Stream fsIn,
Stream fsOut, string Password)
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(Password,
new byte[]
{
0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
0x65, 0x64, 0x76, 0x65, 0x64, 0x65,
0x76
});

TripleDES alg = TripleDES.Create();
alg.Key = pdb.GetBytes(16);
alg.IV = pdb.GetBytes(8);

CryptoStream cs = new CryptoStream(fsOut, alg.CreateEncryptor(),
CryptoStreamMode.Write);

const int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int bytesRead;

try
{
do
{
bytesRead = fsIn.Read(buffer, 0, bufferLen);
cs.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
finally
{
cs.FlushFinalBlock();
// or cs.Close depends on whether to close the underlying stream.
}
}

public static void Decrypt(Stream fsIn,
Stream fsOut, string Password)
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(Password,
new byte[]
{
0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
0x65, 0x64, 0x76, 0x65, 0x64, 0x65,
0x76
});

TripleDES alg = TripleDES.Create();
alg.Key = pdb.GetBytes(16);
alg.IV = pdb.GetBytes(8);

CryptoStream cs = new CryptoStream(fsOut, alg.CreateDecryptor(),
CryptoStreamMode.Write);

const int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int bytesRead;

try
{
do
{
bytesRead = fsIn.Read(buffer, 0, bufferLen);
cs.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
finally
{
cs.FlushFinalBlock();
// or cs.Close depends on whether to close the underlying stream.
}
}

And for reference:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptos
tream.flushfinalblock.aspx
http://msdn.microsoft.com/en-us/library/bb354769.aspx (note the Remarks)

If you have any further questions regarding this issue, please feel free to
post here.

Regards,

Jie Wang ([email protected], remove 'online.')

Microsoft Online Community Support

Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
(e-mail address removed).

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/en-us/subscriptions/aa948868.aspx#notifications.

Note: MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 2 business days is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions. Issues of this
nature are best handled working with a dedicated Microsoft Support Engineer
by contacting Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/en-us/subscriptions/aa948874.aspx
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
 
J

Jie Wang [MSFT]

Hi Andrew,

Any updates on this issue?

If there were still problems, please let me know and I'll see how to fix it.

Thanks,

Jie Wang ([email protected], remove 'online.')

Microsoft Online Community Support

Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
(e-mail address removed).

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/en-us/subscriptions/aa948868.aspx#notifications.

Note: MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 2 business days is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions. Issues of this
nature are best handled working with a dedicated Microsoft Support Engineer
by contacting Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/en-us/subscriptions/aa948874.aspx
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top