• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 615
  • Last Modified:

Simple Text File Encryption (C#)

Can someone provide me an example of how to encrypt a text file that already exists... and also an example to unencrypt it? It doesnt have to be the strongest thing in the world... I just want it to be a step above setting the file parameter to "hidden". Thanks.
0
Pretzel_Jesus
Asked:
Pretzel_Jesus
  • 2
1 Solution
 
jandromedaCommented:
0
 
jandromedaCommented:
Here you go. I have tested this code.
// Encrypt file
			DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider) DESCryptoServiceProvider.Create();
			string key = ASCIIEncoding.ASCII.GetString(desCrypto.Key);
			
			FileStream fsInput = new FileStream(@"C:\InputFile.txt", FileMode.Open, FileAccess.Read);
			FileStream fsEncrypted = new FileStream(@"C:\EncryFile.enc", FileMode.Create, FileAccess.Write);
			
			ICryptoTransform desEncrypt = desCrypto.CreateEncryptor();
			CryptoStream cryptoStream = new CryptoStream(fsEncrypted, desEncrypt, CryptoStreamMode.Write);
			
			byte[] byteArrayInput = new byte[fsInput.Length - 1];
			fsInput.Read(byteArrayInput, 0, byteArrayInput.Length);
			cryptoStream.Write(byteArrayInput, 0, byteArrayInput.Length);
			cryptoStream.Close();
			fsEncrypted.Close();
			fsInput.Close();
			
			// Decrypt the file
			FileStream fsRead = new FileStream(@"C:\EncryFile.enc", FileMode.Open, FileAccess.Read);
			
			ICryptoTransform desDecrypt = desCrypto.CreateDecryptor();
			CryptoStream decryptoStream = new CryptoStream(fsRead, desDecrypt, CryptoStreamMode.Read);
			
			StreamWriter fsDecrypted = new StreamWriter(@"C:\OutputFile.txt");
			StreamReader reader = new StreamReader(decryptoStream);
			string fileText = reader.ReadToEnd();
			fsDecrypted.Write(fileText);
			fsDecrypted.Close();
			decryptoStream.Close();
			fsRead.Close();

Open in new window

0
 
Pretzel_JesusAuthor Commented:
Exactly what I needed thanks!
0

Featured Post

NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now