Last active
August 26, 2017 08:02
-
-
Save JoeSz/64674129f22f6919bd639e267919ce70 to your computer and use it in GitHub Desktop.
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
public static void AES_Encrypt(string inputFile, string password) | |
{ | |
//Source: http://stackoverflow.com/questions/14871238/report-progress-backgroundworker-from-different-class-c-sharp | |
//Source: http://stackoverflow.com/questions/27645527/aes-encryption-on-large-files | |
//generate random salt | |
byte[] salt = Security.GenerateRandomSalt(32); | |
//create output file name | |
FileStream fsCrypt = new FileStream(inputFile + ".aes", FileMode.Create); | |
//convert password string to byte arrray | |
byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password); | |
//Set Rijndael symmetric encryption algorithm | |
RijndaelManaged AES = new RijndaelManaged(); | |
AES.KeySize = 256; | |
AES.BlockSize = 128; | |
AES.Padding = PaddingMode.PKCS7; | |
//http://stackoverflow.com/questions/2659214/why-do-i-need-to-use-the-rfc2898derivebytes-class-in-net-instead-of-directly | |
//"What it does is repeatedly hash the user password along with the salt." | |
//High iteration counts. | |
var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000); | |
AES.Key = key.GetBytes(AES.KeySize / 8); | |
AES.IV = key.GetBytes(AES.BlockSize / 8); | |
//Cipher modes: | |
//http://security.stackexchange.com/questions/52665/which-is-the-best-cipher-mode-and-padding-mode-for-aes-encryption | |
AES.Mode = CipherMode.CFB; | |
//write salt to the begining of the output file | |
fsCrypt.Write(salt, 0, salt.Length); | |
CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateEncryptor(), CryptoStreamMode.Write); | |
FileStream fsIn = new FileStream(inputFile, FileMode.Open); | |
//create a buffer (1mb) so only this amount will allocate in the memory and not the whole file | |
byte[] buffer = new byte[1048576]; | |
int read; | |
long y = 0; | |
try | |
{ | |
while ((read = fsIn.Read(buffer, 0, buffer.Length)) > 0) | |
{ | |
Application.DoEvents(); | |
// -> for responsive GUI, using Task will be better! | |
//JSEncryptorPro uses background worker, I left it here like this, so if somebody | |
//want to "copy-paste" the code, can use immediately | |
cs.Write(buffer, 0, read); | |
} | |
//close up | |
fsIn.Close(); | |
} | |
catch (Exception ex) | |
{ | |
Debug.WriteLine("Error: " + ex.Message); | |
} | |
finally | |
{ | |
cs.Close(); | |
fsCrypt.Close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment