private static async Task DecryptAsync(string InputPath) { // Get password from user. // TODO: Hide and confirm password. ThreadsafeConsole.Write("Enter password: "******"Output filename is {outputFilename}."); // Generate key from password (provided by user) and salt (stored in encrypted file). using (var keyDerivation = KeyDerivation.Create(encryptedFileHeader.KeyDerivationAlgorithm, password, encryptedFileHeader.Salt, encryptedFileHeader.KeyDerivationIterations)) { var key = keyDerivation.GetBytes(encryptedFileHeader.KeyLength); ThreadsafeConsole.WriteLine($"Encryption key (derived from password and salt) is {Convert.ToBase64String(key)}."); ThreadsafeConsole.WriteLine($"Cipher initialization vector is {Convert.ToBase64String(encryptedFileHeader.InitializationVector)}."); // Create cipher from key (see above) plus algorithm name and initialization vector (stored in unencrypted header at beginning of encrypted file). // Create decrypting input stream. using (var cipher = Cipher.Create(encryptedFileHeader.CipherAlgorithm)) using (var decryptor = cipher.CreateDecryptor(key, encryptedFileHeader.InitializationVector)) await using (var cryptoStream = new CryptoStream(inputFileStream, decryptor, CryptoStreamMode.Read)) await using (var outputFileStream = File.Open(outputFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { // To limit memory usage, repeatedly read a small block from input stream and write it to the decrypted output stream. var buffer = new byte[cipher.BlockSize]; int bytesRead; while ((bytesRead = await cryptoStream.ReadAsync(buffer, 0, buffer.Length)) > 0) { await outputFileStream.WriteAsync(buffer, 0, bytesRead); } } } } var encryptionDuration = _stopwatch.Elapsed - encryptionStart; ThreadsafeConsole.WriteLine($"Wrote decrypted file to {outputFilename}."); ThreadsafeConsole.WriteLine($"Decryption took {encryptionDuration.TotalSeconds.ToString(_elapsedSecondsFormat)} seconds."); }
// TODO: Add progress bar. private static async Task EncryptAsync(EncryptedFileHeader EncryptedFileHeader) { const string encryptedFileExtension = ".encrypted"; var inputPathIsFile = File.Exists(EncryptedFileHeader.Filename); if (!inputPathIsFile && !Directory.Exists(EncryptedFileHeader.Filename)) { throw new Exception($"{EncryptedFileHeader.Filename} input path does not exist."); } ThreadsafeConsole.WriteLine(inputPathIsFile ? "InputPath is a file." : "InputPath is a directory."); // TODO: Support encrypting entire directories using System.IO.Compression.ZipFile class. if (!inputPathIsFile) { throw new NotSupportedException("Encrypting directories is not supported."); } // Get password from user. // TODO: Hide and confirm password. ThreadsafeConsole.WriteLine(); ThreadsafeConsole.Write("Enter password: "******"Output filename is {outputFilename}."); var encryptionStart = _stopwatch.Elapsed; await using (var inputFileStream = File.Open(EncryptedFileHeader.Filename, FileMode.Open, FileAccess.Read, FileShare.Read)) await using (var outputFileStream = File.Open(outputFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { // Generate key from password and random salt. using (var random = new RNGCryptoServiceProvider()) { random.GetBytes(EncryptedFileHeader.Salt); } using (var keyDerivation = KeyDerivation.Create(EncryptedFileHeader.KeyDerivationAlgorithm, password, EncryptedFileHeader.Salt, EncryptedFileHeader.KeyDerivationIterations)) using (var cipher = Cipher.Create(EncryptedFileHeader.CipherAlgorithm)) { var key = keyDerivation.GetBytes(EncryptedFileHeader.KeyLength); ThreadsafeConsole.WriteLine($"Encryption key (derived from password and a random salt) is {Convert.ToBase64String(key)}."); // Create cipher and generate initialization vector. // Generate a new initialization vector for each encryption to prevent identical plaintexts from producing identical ciphertexts when encrypted using the same key. cipher.GenerateIV(); EncryptedFileHeader.InitializationVector = new byte[cipher.IV.Length]; cipher.IV.CopyTo(EncryptedFileHeader.InitializationVector, 0); ThreadsafeConsole.WriteLine($"Cipher initialization vector is {Convert.ToBase64String(EncryptedFileHeader.InitializationVector)}."); // Write integer length of encrypted file header followed by the the header bytes. var fileHeaderBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(EncryptedFileHeader)); await outputFileStream.WriteAsync(BitConverter.GetBytes(fileHeaderBytes.Length)); await outputFileStream.WriteAsync(fileHeaderBytes); // Create encrypting output stream. var buffer = new byte[cipher.BlockSize]; using (var encryptor = cipher.CreateEncryptor(key, EncryptedFileHeader.InitializationVector)) await using (var cryptoStream = new CryptoStream(outputFileStream, encryptor, CryptoStreamMode.Write)) { // To limit memory usage, repeatedly read a small block from input stream and write it to the encrypted output stream. int bytesRead; while ((bytesRead = await inputFileStream.ReadAsync(buffer, 0, buffer.Length)) > 0) { await cryptoStream.WriteAsync(buffer, 0, bytesRead); } } } } var encryptionDuration = _stopwatch.Elapsed - encryptionStart; ThreadsafeConsole.WriteLine($"Wrote encrypted file to {outputFilename}."); ThreadsafeConsole.WriteLine($"Encryption took {encryptionDuration.TotalSeconds.ToString(_elapsedSecondsFormat)} seconds."); }