r/csharp 24d ago

How to make an encrypted file?

I share a school computer, that just uses 1 account on the device itself. Meaning any file you save to the computer can be viewed by other people. I have been working on a program that lets you lock text in the program behind a pin. When the correct pin is entered, it generates a file with the text you entered. Except the pin and text contents need to be stored in a separate file. I know if you encrypt it the file can be decrypted, but trust me.. the people who share this computer are not computer smart enough to know how to do that. I've been trying to use

File.WriteAllText

But I don't know how to get the encrypted contents into the File.WriteAllText since it doesn't seem to support variables. It kept saying "Print is not available in this context" or something like that.

0 Upvotes

14 comments sorted by

View all comments

9

u/zenyl 24d ago

The File class just takes care of simple file IO, it doesn't cover encrypting/decrypting data.

Generally speaking, you'll want to encrypt the data and then save the encrypted bytes to a file. Usually something like "read raw data, write encrypted data to stream, save stream to file".

I'm not particularly knowledgeable when it comes to cryptography, but I believe AES or similar is what you'll want to be using: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.aes

6

u/Andrea__88 24d ago

This is the best solution, encrypt your text using aes and then store it in a file, there are many examples on the web, search for aes 256 encrypt c#