Skip to content

Instantly share code, notes, and snippets.

@nakov
Created March 10, 2021 17:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nakov/1d39c4513cff83b8a735d7dc883dfe18 to your computer and use it in GitHub Desktop.
Save nakov/1d39c4513cff83b8a735d7dc883dfe18 to your computer and use it in GitHub Desktop.
C# Encrypt / Decrypt File with XOR
using System.IO;
void EncryptFile(string inputFile, string outputFile)
{
using (var fin = new FileStream(inputFile, FileMode.Open))
using (var fout = new FileStream(outputFile, FileMode.Create))
{
byte[] buffer = new byte[4096];
while (true)
{
int bytesRead = fin.Read(buffer);
if (bytesRead == 0)
break;
EncryptBytes(buffer, bytesRead);
fout.Write(buffer, 0, bytesRead);
}
}
}
const byte Secret = 183;
void EncryptBytes(byte[] buffer, int count)
{
for (int i = 0; i < count; i++)
buffer[i] = (byte)(buffer[i] ^ Secret);
}
EncryptFile("example.png", "example-encrypted.png");
EncryptFile("example-encrypted.png", "example-original.png");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment