Question Partial file encryption


New member
Apr 24, 2014
Programming Experience
Good day everyone,
I'm doing some job with file encryption and want to do partial file encryption.
Let's say i have text file with data:
123456789999999888844565452 and want to encrypt only part of file
xxxxxxxxxx999999888844565452 - where x encrypted part.

How I can do this ?
I've tried to do this but everything failed because when decrypting algorithm throws "invalid password" error.
You don't actually encrypt a file. You encrypt data. What you do with that data is then completely up to you. You can write to a file if you want or you can do something else with it. If you have some text and you want to encrypt part of it then that's exactly what you do. You write part of the plain text to the file, then you encrypt part of the text and write the result to the file, then you write the rest of the text to the file. To write text to any Stream you use a StreamWriter and to encrypt data you use a CryptoStream. That means that to write plain text, then encrypted data and then plain text, you'll need to create a StreamWriter on top of a FileStream, then a StreamWriter on top of a CryptoStream on top of a FileStream, then a StreamWriter on top of FileStream again. You'll need to fill in the details for yourself but here's a simple example of how you might do that:
private void WriteTextToStream(string text, Stream stream)
    using (var writer = new StreamWriter(stream))
using (var file = new FileStream(filePath, FileMode.Create))
    this.WriteTextToStream("First Line", file);

using (var file = new FileStream(filePath, FileMode.Append))
using (var encryptor = new CryptoStream(file, transform, CryptoStreamMode.Write))
    this.WriteTextToStream("Second Line", encryptor);

using (var file = new FileStream(filePath, FileMode.Append))
    this.WriteTextToStream("Third Line", file);
Reading the file back will be basically the same except that you'll use a StreamReader instead of a StreamWriter. You'll need to know exactly how much to read for each part too, so you have to either know that ahead of time or be able to read it from the file.
Top Bottom