Skip to content

Instantly share code, notes, and snippets.

@MichaelTaylor3D
Forked from HirbodBehnam/AES-GCM-File.cs
Created May 4, 2020 01:02
Show Gist options
  • Save MichaelTaylor3D/986de0dd8ccd4031774b39161c297f26 to your computer and use it in GitHub Desktop.
Save MichaelTaylor3D/986de0dd8ccd4031774b39161c297f26 to your computer and use it in GitHub Desktop.
A simple program to encrypt and decrypt a file using AES-GCM and Bouncy Castle
using System;
using System.IO;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
namespace TestConsole
{
class Program
{
static void Main()
{
// most of the code is from https://stackoverflow.com/a/26434031/4213397
// FUCKED UP security; Use RNGCryptoServiceProvider
Random rnd = new Random();
var key = new byte[16];
var nonce = new byte[12];
rnd.NextBytes(key);
rnd.NextBytes(nonce);
using (Stream sr = File.OpenRead("words.txt"))
{
using (Stream sw = File.OpenWrite("words.aes"))
{
var cipher = new GcmBlockCipher(new AesEngine());
cipher.Init(true,new AeadParameters(new KeyParameter(key), 128, nonce));
byte[] input = new byte[8192];
byte[] output = new byte[cipher.GetBlockSize() + cipher.GetOutputSize (input.Length)];
int bytesRead;
do
{
bytesRead = sr.Read(input, 0, input.Length);
if (bytesRead > 0)
{
int count = cipher.ProcessBytes(input, 0, bytesRead, output, 0);
sw.Write(output,0,count);
}
} while (bytesRead > 0);
int lastSize = cipher.DoFinal(output, 0);
sw.Write(output,0,lastSize);
}
}
using (Stream sr = File.OpenRead("words.aes"))
{
using (Stream sw = File.OpenWrite("words.final.txt"))
{
var cipher = new GcmBlockCipher(new AesEngine());
cipher.Init(false,new AeadParameters(new KeyParameter(key), 128, nonce));
byte[] input = new byte[8192];
byte[] output = new byte[cipher.GetBlockSize() + cipher.GetOutputSize (input.Length)];
int bytesRead;
do
{
bytesRead = sr.Read(input, 0, input.Length);
if (bytesRead > 0)
{
int count = cipher.ProcessBytes(input, 0, bytesRead, output, 0);
sw.Write(output,0,count);
}
} while (bytesRead > 0);
int lastSize = cipher.DoFinal(output, 0);
sw.Write(output,0,lastSize);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment