Created
February 1, 2020 18:41
-
-
Save HirbodBehnam/35e10a34dea05baf6ae80b62b722f9a8 to your computer and use it in GitHub Desktop.
A simple program to encrypt and decrypt a file using AES-GCM and Bouncy Castle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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