private void StartEncryption() { try { string inFile = filenameBox.Text; string outFile = filenameBox.Text + ".fcfe"; string password = passwordBox.Text; progressBar.Visibility = System.Windows.Visibility.Visible; progressBar.Minimum = 0; progressBar.Maximum = 100; updatePbDelegate = new UpdateProgressBarDelegate(progressBar.SetValue); CryptoProgressCallBack cb = new CryptoProgressCallBack(this.ProgressCallBackEncrypt); CryptoHelp.EncryptFile(inFile, outFile, password, cb); progressBar.Value = 0; filenameBox.Text = ""; passwordBox.Text = ""; progressBar.Visibility = System.Windows.Visibility.Collapsed; } catch (Exception ex) { encryptButton.IsEnabled = true; MessageBoxResult result = MessageBox.Show(ex.Message); } }
/// <summary> /// Decrypts the file. /// </summary> private void DecryptFile() { string caption = "Decryption"; if (!(string.IsNullOrEmpty(_txtPassword.Text))) { if (!(_txtPassword.Text == _txtConfirmPassword.Text)) { MessageBox.Show("Password and ConfirmPassword don't match, please confirm the password again.", caption, MessageBoxButtons.OK, MessageBoxIcon.Warning); _txtConfirmPassword.Text = string.Empty; _txtConfirmPassword.Focus(); } else { if (_txtFromFolder.Text != String.Empty) { if (File.Exists(_txtFromFolder.Text)) { if (_encExtension == Path.GetExtension(_txtFromFolder.Text)) { string password = _txtPassword.Text; CryptoProgressCallBack cb = new CryptoProgressCallBack(this.ProgressCallBackDecrypt); _tsStatusInfoLabel.Text = "In Progress..."; CryptoHelper.DecryptFile(_txtFromFolder.Text, _txtToFolder.Text, password, cb); _pbProgress.Value = 0; _tsStatusInfoLabel.Text = "File Decryption Complete."; } else { MessageBox.Show("Please select encrypted file with extension enc to decrypt.", caption, MessageBoxButtons.OK, MessageBoxIcon.Warning); _btnToFolderBrowse.Focus(); } } else { MessageBox.Show("File doesn't exist, Please select the file to decrypt.", caption, MessageBoxButtons.OK, MessageBoxIcon.Warning); _btnFromFolderBrowse.Focus(); } } else { MessageBox.Show("Please select file to decrypt.", caption, MessageBoxButtons.OK, MessageBoxIcon.Warning); _btnFromFolderBrowse.Focus(); } } } else { MessageBox.Show("Please enter password and confirm it.", caption, MessageBoxButtons.OK, MessageBoxIcon.Warning); _txtPassword.Focus(); } }
/// <summary> /// This takes an input Stream and encrypts it into the output Stream /// </summary> /// <param name="fin">the Stream to encrypt</param> /// <param name="fout">the Stream to write the encrypted data to</param> /// <param name="password">the password for use as the key</param> /// <param name="callback">the method to call to notify of progress</param> public static void EncryptStream(Stream fin, Stream fout, string password, CryptoProgressCallBack callback) { long lSize = fin.Length; // the size of the input file for storing int size = (int)lSize; // the size of the input file for progress byte[] bytes = new byte[BUFFER_SIZE]; // the buffer int read = -1; // the amount of bytes read from the input file int value = 0; // the amount overall read from the input file for progress // generate IV and Salt byte[] IV = GenerateRandomBytes(16); byte[] salt = GenerateRandomBytes(16); // create the crypting object SymmetricAlgorithm sma = CreateRijndael(password, salt); sma.IV = IV; // write the IV and salt to the beginning of the file fout.Write(IV, 0, IV.Length); fout.Write(salt, 0, salt.Length); // create the hashing and crypto streams HashAlgorithm hasher = SHA256.Create(); using (CryptoStream cout = new CryptoStream(fout, sma.CreateEncryptor(), CryptoStreamMode.Write), chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write)) { // write the size of the file to the output file BinaryWriter bw = new BinaryWriter(cout); bw.Write(lSize); // write the file cryptor tag to the file bw.Write(FC_TAG); // read and the write the bytes to the crypto stream in BUFFER_SIZEd chunks while ((read = fin.Read(bytes, 0, bytes.Length)) != 0) { cout.Write(bytes, 0, read); chash.Write(bytes, 0, read); value += read; callback(0, size, value); } // flush and close the hashing object chash.Flush(); chash.Close(); // read the hash byte[] hash = hasher.Hash; // write the hash to the end of the file cout.Write(hash, 0, hash.Length); // flush and close the cryptostream cout.Flush(); cout.Close(); } }
/// <summary> /// Encrypts the file. /// </summary> private string EncryptFile() { string caption = "Encryption"; string encryptFile = string.Empty; if (!(string.IsNullOrEmpty(_txtPassword.Text))) { if (!(_txtPassword.Text == _txtConfirmPassword.Text)) { MessageBox.Show("Password and ConfirmPassword don't match, please confirm the password again.", caption, MessageBoxButtons.OK, MessageBoxIcon.Warning); _txtConfirmPassword.Text = string.Empty; _txtConfirmPassword.Focus(); } else { if (_txtFromFolder.Text != String.Empty) { if (File.Exists(_txtFromFolder.Text)) { string inFile = _txtFromFolder.Text; string outFolder = _txtToFolder.Text; string password = _txtPassword.Text; CryptoProgressCallBack cb = new CryptoProgressCallBack(this.ProgressCallBackEncrypt); _tsStatusInfoLabel.Text = "In Progress ..."; encryptFile = CryptoHelper.EncryptFile(inFile, outFolder, password, cb); _pbProgress.Value = 0; _tsStatusInfoLabel.Text = "File Encryption Complete."; } else { MessageBox.Show("File doesn't exist, Please select the file to Encrypt.", caption, MessageBoxButtons.OK, MessageBoxIcon.Warning); _btnFromFolderBrowse.Focus(); } } else { MessageBox.Show("Please select file to Encrypt.", caption, MessageBoxButtons.OK, MessageBoxIcon.Warning); _btnFromFolderBrowse.Focus(); } } } else { MessageBox.Show("Please enter password and confirm it to Encrypt and Generate Hash.", caption, MessageBoxButtons.OK, MessageBoxIcon.Warning); _txtPassword.Focus(); } return(encryptFile); }
/// <summary> /// takes an input file and decrypts it to the output file /// </summary> /// <param name="inFile">the file to decrypt</param> /// <param name="outFile">the to write the decrypted data to</param> /// <param name="password">the password used as the key</param> /// <param name="callback">the method to call to notify of progress</param> public static void DecryptFile(string inFile, string outFile, string password, CryptoProgressCallBack callback) { // NOTE: The encrypting algo was so much easier... // create and open the file streams using(FileStream fin = File.OpenRead(inFile), fout = File.OpenWrite(outFile)) { int size = (int)fin.Length; // the size of the file for progress notification byte[] bytes = new byte[BUFFER_SIZE]; // byte buffer int read = -1; // the amount of bytes read from the stream int value = 0; int outValue = 0; // the amount of bytes written out // read off the IV and Salt byte[] IV = new byte[16]; fin.Read(IV,0,16); byte[] salt = new byte[16]; fin.Read(salt,0,16); // create the crypting stream SymmetricAlgorithm sma = EncryptDecrypt.CreateRijndael(password,salt); sma.IV = IV; value = 32; // the value for the progress long lSize = -1; // the size stored in the input stream // create the hashing object, so that we can verify the file HashAlgorithm hasher = SHA256.Create(); // create the cryptostreams that will process the file using(CryptoStream cin = new CryptoStream(fin,sma.CreateDecryptor(),CryptoStreamMode.Read), chash = new CryptoStream(Stream.Null,hasher,CryptoStreamMode.Write)) { // read size from file BinaryReader br = new BinaryReader(cin); lSize = br.ReadInt64(); ulong tag = br.ReadUInt64(); if(FC_TAG != tag) throw new CryptoHelpException("File Corrupted!"); //determine number of reads to process on the file long numReads = lSize / BUFFER_SIZE; // determine what is left of the file, after numReads long slack = (long)lSize % BUFFER_SIZE; // read the buffer_sized chunks for(int i = 0; i < numReads; ++i) { read = cin.Read(bytes,0,bytes.Length); fout.Write(bytes,0,read); chash.Write(bytes,0,read); value += read; outValue += read; callback(0,size,value); } // now read the slack if(slack > 0) { read = cin.Read(bytes,0,(int)slack); fout.Write(bytes,0,read); chash.Write(bytes,0,read); value += read; outValue += read; callback(0,size,value); } // flush and close the hashing stream chash.Flush(); chash.Close(); // flush and close the output file fout.Flush(); fout.Close(); // read the current hash value byte[] curHash = hasher.Hash; // get and compare the current and old hash values byte[] oldHash = new byte[hasher.HashSize / 8]; read = cin.Read(oldHash,0,oldHash.Length); if((oldHash.Length != read) || (!CheckByteArrays(oldHash,curHash))) throw new CryptoHelpException("File Corrupted!"); } // make sure the written and stored size are equal if(outValue != lSize) throw new CryptoHelpException("File Sizes don't match!"); } }
/// <summary> /// This takes an input file and encrypts it into the output file /// </summary> /// <param name="inFile">the file to encrypt</param> /// <param name="outFile">the file to write the encrypted data to</param> /// <param name="password">the password for use as the key</param> /// <param name="callback">the method to call to notify of progress</param> public static void EncryptFile(string inFile, string outFile, string password, CryptoProgressCallBack callback) { using(FileStream fin = File.OpenRead(inFile), fout = File.OpenWrite(outFile)) { long lSize = fin.Length; // the size of the input file for storing int size = (int)lSize; // the size of the input file for progress byte[] bytes = new byte[BUFFER_SIZE]; // the buffer int read = -1; // the amount of bytes read from the input file int value = 0; // the amount overall read from the input file for progress // generate IV and Salt byte[] IV = GenerateRandomBytes(16); byte[] salt = GenerateRandomBytes(16); // create the crypting object SymmetricAlgorithm sma = CryptoHelp.CreateRijndael(password, salt); sma.IV = IV; // write the IV and salt to the beginning of the file fout.Write(IV,0,IV.Length); fout.Write(salt,0,salt.Length); // create the hashing and crypto streams HashAlgorithm hasher = SHA256.Create(); using(CryptoStream cout = new CryptoStream(fout,sma.CreateEncryptor(),CryptoStreamMode.Write), chash = new CryptoStream(Stream.Null,hasher,CryptoStreamMode.Write)) { // write the size of the file to the output file BinaryWriter bw = new BinaryWriter(cout); bw.Write(lSize); // write the file cryptor tag to the file bw.Write(FC_TAG); // read and the write the bytes to the crypto stream in BUFFER_SIZEd chunks while( (read = fin.Read(bytes,0,bytes.Length)) != 0 ) { cout.Write(bytes,0,read); chash.Write(bytes,0,read); value += read; callback(0,size,value); } // flush and close the hashing object chash.Flush(); chash.Close(); // read the hash byte[] hash = hasher.Hash; // write the hash to the end of the file cout.Write(hash,0,hash.Length); // flush and close the cryptostream cout.Flush(); cout.Close(); } } }
/// <summary> /// This takes an input file and encrypts it into the output file /// </summary> /// <param name="inFile">the file to encrypt</param> /// <param name="outFolder">the folder to write the encrypted data to</param> /// <param name="password">the password for use as the key</param> /// <param name="callback">the method to call to notify of progress</param> public static string EncryptFile(string inFile, string outFolder, string password, CryptoProgressCallBack callback) { try { string inFileName = Path.GetFileName(inFile); string myFolderName = Convert.ToString(DateTime.Now.ToString("yyyyMMddhhmmss")) + "_MyWayCryptUtil"; string outPath = string.Empty; // create output folder if (!(string.IsNullOrEmpty(outFolder))) { outPath = Path.Combine(outFolder, myFolderName); } else { outPath = Path.Combine(Path.GetDirectoryName(inFile), myFolderName); } //Create output directory if it doesn't exist. if (!Directory.Exists(outPath)) { Directory.CreateDirectory(outPath); } string outFile = outPath + "\\" + inFileName + ".enc"; FileStream fin = File.OpenRead(inFile), fout = File.OpenWrite(outFile); { long lSize = fin.Length; // the size of the input file for storing int size = (int)lSize; // the size of the input file for progress byte[] bytes = new byte[BUFFER_SIZE]; // the buffer int read = -1; // the amount of bytes read from the input file int value = 0; // the amount overall read from the input file for progress // generate IV and Salt byte[] IV = GenerateRandomBytes(16); byte[] salt = GenerateRandomBytes(16); // create the crypting object SymmetricAlgorithm sma = CryptoHelper.CreateRijndael(password, salt); sma.IV = IV; // write the IV and salt to the beginning of the file fout.Write(IV, 0, IV.Length); fout.Write(salt, 0, salt.Length); // create the hashing and crypto streams HashAlgorithm hasher = SHA256.Create(); CryptoStream cout = new CryptoStream(fout, sma.CreateEncryptor(), CryptoStreamMode.Write), chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write); { // write the size of the file to the output file BinaryWriter bw = new BinaryWriter(cout); bw.Write(lSize); // write the file cryptor tag to the file bw.Write(FC_TAG); // read and the write the bytes to the crypto stream in BUFFER_SIZEd chunks while ((read = fin.Read(bytes, 0, bytes.Length)) != 0) { cout.Write(bytes, 0, read); chash.Write(bytes, 0, read); value += read; callback(0, size, value); } // flush and close the hashing object chash.Flush(); chash.Close(); // read the hash byte[] hash = hasher.Hash; // write the hash to the end of the file cout.Write(hash, 0, hash.Length); // flush and close the cryptostream cout.Flush(); cout.Close(); } } // Copy utility and config file to the output folder with only decrypt option. string workingDirectory = Application.StartupPath; string cryptUtilFile = workingDirectory + "\\CryptoUtility.exe"; string cryptUtilConfigFile = workingDirectory + "\\CryptoUtility.exe.config"; string cryptUtilFileCopy = outPath + "\\CryptoUtility.exe"; string configFile = outPath + "\\CryptoUtility.exe.config"; if (File.Exists(cryptUtilFile)) { File.Copy(cryptUtilFile, cryptUtilFileCopy, true); } StreamReader sr = new StreamReader(cryptUtilConfigFile); StringBuilder sb = new StringBuilder(sr.ReadToEnd()); sr.Close(); string options = "value=\"Decrypt\""; sb.Replace("value=\"Full\"", options); StreamWriter sw = new StreamWriter(configFile, false); sw.Write(sb.ToString()); sw.Close(); return(outFile); } catch (Exception ex) { throw new Exception(ex.Message); } }
/// <summary> /// takes an input file and decrypts it to the output file /// </summary> /// <param name="inFile">the file to decrypt</param> /// <param name="ToFolder">the to write the decrypted data to</param> /// <param name="password">the password used as the key</param> /// <param name="callback">the method to call to notify of progress</param> public static void DecryptFile(string inFile, string ToFolder, string password, CryptoProgressCallBack callback) { string outFile = string.Empty; FileStream fin = null, fout = null; try { int index = inFile.LastIndexOf(".enc"); string orgFile = inFile.Substring(0, index); string outFileName = Path.GetFileName(orgFile); if (!(string.IsNullOrEmpty(ToFolder))) { outFile = Path.Combine(ToFolder, outFileName); } else { outFile = orgFile; } // NOTE: The encrypting algo was so much easier... // create and open the file streams fin = File.OpenRead(inFile); fout = File.OpenWrite(outFile); { int size = (int)fin.Length; // the size of the file for progress notification byte[] bytes = new byte[BUFFER_SIZE]; // byte buffer int read = -1; // the amount of bytes read from the stream int value = 0; int outValue = 0; // the amount of bytes written out // read off the IV and Salt byte[] IV = new byte[16]; fin.Read(IV, 0, 16); byte[] salt = new byte[16]; fin.Read(salt, 0, 16); // create the crypting stream SymmetricAlgorithm sma = CryptoHelper.CreateRijndael(password, salt); sma.IV = IV; value = 32; // the value for the progress long lSize = -1; // the size stored in the input stream // create the hashing object, so that we can verify the file HashAlgorithm hasher = SHA256.Create(); // create the cryptostreams that will process the file CryptoStream cin = new CryptoStream(fin, sma.CreateDecryptor(), CryptoStreamMode.Read), chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write); { // read size from file BinaryReader br = new BinaryReader(cin); lSize = br.ReadInt64(); ulong tag = br.ReadUInt64(); if (FC_TAG != tag) { throw new CryptoHelperException("Password Incorrect, Please provide the correct password."); } //determine number of reads to process on the file long numReads = lSize / BUFFER_SIZE; // determine what is left of the file, after numReads long slack = (long)lSize % BUFFER_SIZE; // read the buffer_sized chunks for (int i = 0; i < numReads; ++i) { read = cin.Read(bytes, 0, bytes.Length); fout.Write(bytes, 0, read); chash.Write(bytes, 0, read); value += read; outValue += read; callback(0, size, value); } // now read the slack if (slack > 0) { read = cin.Read(bytes, 0, (int)slack); fout.Write(bytes, 0, read); chash.Write(bytes, 0, read); value += read; outValue += read; callback(0, size, value); } // flush and close the hashing stream chash.Flush(); chash.Close(); // flush and close the output file fout.Flush(); fout.Close(); // read the current hash value byte[] curHash = hasher.Hash; // get and compare the current and old hash values byte[] oldHash = new byte[hasher.HashSize / 8]; read = cin.Read(oldHash, 0, oldHash.Length); if ((oldHash.Length != read) || (!CheckByteArrays(oldHash, curHash))) { throw new CryptoHelperException("File Corrupted!"); } } // make sure the written and stored size are equal if (outValue != lSize) { throw new CryptoHelperException("File Sizes don't match!"); } } } catch (Exception ex) { // Delete the outFile if it was created. if (fout != null) { fout.Flush(); fout.Close(); } if (File.Exists(outFile)) { File.Delete(outFile); } throw new Exception(ex.Message); } }
/// <summary> /// takes an input file and decrypts it to the output file /// </summary> /// <param name="inFile">the file to decrypt</param> /// <param name="outFile">the to write the decrypted data to</param> /// <param name="password">the password used as the key</param> /// <param name="callback">the method to call to notify of progress</param> public static void DecryptFile(string inFile, string outFile, string password, CryptoProgressCallBack callback) { // NOTE: The encrypting algo was so much easier... // create and open the file streams using (FileStream fin = File.OpenRead(inFile), fout = File.OpenWrite(outFile)) { int size = (int)fin.Length; // the size of the file for progress notification byte[] bytes = new byte[BUFFER_SIZE]; // byte buffer int read = -1; // the amount of bytes read from the stream int value = 0; int outValue = 0; // the amount of bytes written out // read off the IV and Salt byte[] IV = new byte[16]; fin.Read(IV, 0, 16); byte[] salt = new byte[16]; fin.Read(salt, 0, 16); // create the crypting stream SymmetricAlgorithm sma = CryptoHelp.CreateRijndael(password, salt); sma.IV = IV; value = 32; // the value for the progress long lSize = -1; // the size stored in the input stream // create the hashing object, so that we can verify the file HashAlgorithm hasher = SHA256.Create(); // create the cryptostreams that will process the file using (CryptoStream cin = new CryptoStream(fin, sma.CreateDecryptor(), CryptoStreamMode.Read), chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write)) { // read size from file BinaryReader br = new BinaryReader(cin); lSize = br.ReadInt64(); ulong tag = br.ReadUInt64(); if (FC_TAG != tag) { throw new CryptoHelpException("File Corrupted!"); } //determine number of reads to process on the file long numReads = lSize / BUFFER_SIZE; // determine what is left of the file, after numReads long slack = (long)lSize % BUFFER_SIZE; // read the buffer_sized chunks for (int i = 0; i < numReads; ++i) { read = cin.Read(bytes, 0, bytes.Length); fout.Write(bytes, 0, read); chash.Write(bytes, 0, read); value += read; outValue += read; callback(0, size, value); Thread.Sleep(100); } // now read the slack if (slack > 0) { read = cin.Read(bytes, 0, (int)slack); fout.Write(bytes, 0, read); chash.Write(bytes, 0, read); value += read; outValue += read; callback(0, size, value); } // flush and close the hashing stream chash.Flush(); chash.Close(); // flush and close the output file fout.Flush(); fout.Close(); // read the current hash value byte[] curHash = hasher.Hash; // get and compare the current and old hash values byte[] oldHash = new byte[hasher.HashSize / 8]; read = cin.Read(oldHash, 0, oldHash.Length); if ((oldHash.Length != read) || (!CheckByteArrays(oldHash, curHash))) { throw new CryptoHelpException("File Corrupted!"); } } // make sure the written and stored size are equal if (outValue != lSize) { throw new CryptoHelpException("File Sizes don't match!"); } } }
private void DoCheckFile() { if (!File.Exists(FILE_NAME)) { if (!File.Exists(ENCRYPTED_FILE_NAME)) { return; } else { CryptoProgressCallBack cb = new CryptoProgressCallBack(this.ProgressCallBackDecrypt); FileCrypt.DecryptFile(ENCRYPTED_FILE_NAME, FILE_NAME, "", cb); if (File.Exists(ENCRYPTED_FILE_NAME)) File.Delete(ENCRYPTED_FILE_NAME); return; //TODO Decrypt Encrypted File back to xml format } } }
public bool DoPreferrentialReordering( ScreenGroup _Group,PlanType _PlanType,string _Year,string _DistId,string _DivnId,string _MultiEUSCode) { try { //this.USER_NAME = USER_NAME; this.SCREEN_NAME = _Group; this.PLAN_TYPE = _PlanType; this.YEAR = _Year; this.DIST_ID = _DistId; this.DIVN_ID = _DivnId; this.MULTI_EUS_CODE = _MultiEUSCode; bool File_Not_Found = false; if (!File.Exists(FILE_NAME)) { if (!File.Exists(ENCRYPTED_FILE_NAME)) { DoCreateRowOrderingFile(); File_Not_Found = true; } else { CryptoProgressCallBack cb = new CryptoProgressCallBack(this.ProgressCallBackDecrypt); FileCrypt.DecryptFile(ENCRYPTED_FILE_NAME, FILE_NAME, "", cb); if (File.Exists(ENCRYPTED_FILE_NAME)) File.Delete(ENCRYPTED_FILE_NAME); File_Not_Found = false; } //DoAddUserToConfigurationFile(); } if (!File_Not_Found) { DoCheckFileConfig(); if (EUS_EXIST_IN_DATA_SECTION && SCREEN_EXIST_IN_DATA_SECTION && RECORD_SPEC_EXIST_IN_DATA_SECTION) { if (!DoReordering()) { //TODO throw exception } //ReorderAssociatedGrids(); } } return false; } catch { return true; } }
public static MemoryStream EncryptMemory(string inFile, MemoryStream mout, string password, CryptoProgressCallBack callback) { // string vol=GetDriveVolumeProperties("C"); // MessageBox.Show(vol); using (FileStream fin = File.OpenRead(inFile)) { long lSize = fin.Length; // the size of the input file for storing int size = (int)lSize; // the size of the input file for progress byte[] bytes = new byte[BUFFER_SIZE]; // the buffer int read = -1; // the amount of bytes read from the input file int value = 0; // the amount overall read from the input file for progress // generate IV and Salt byte[] IV = GenerateRandomBytes(16); byte[] salt = GenerateRandomBytes(16); // create the crypting object SymmetricAlgorithm sma = CryptoHelp.CreateRijndael(password, salt); sma.IV = IV; // write the IV and salt to the beginning of the file mout.Write(IV, 0, IV.Length); mout.Write(salt, 0, salt.Length); // create the hashing and crypto streams HashAlgorithm hasher = SHA256.Create(); using (CryptoStream cout = new CryptoStream(mout, sma.CreateEncryptor(), CryptoStreamMode.Write), chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write)) { // write the size of the file to the output file BinaryWriter bw = new BinaryWriter(cout); bw.Write(lSize); // write the file cryptor tag to the file bw.Write(FC_TAG); // BinaryWriter mbw = new BinaryWriter(mout); // mbw.Write(lSize); // mbw.Write(FC_TAG); // read and the write the bytes to the crypto stream in BUFFER_SIZEd chunks while ((read = fin.Read(bytes, 0, bytes.Length)) != 0) { cout.Write(bytes, 0, read); // mout.Write(bytes,0,read); chash.Write(bytes, 0, read); value += read; if (callback != null) { callback(0, size, value); } } // flush and close the hashing object chash.Flush(); chash.Close(); // read the hash byte[] hash = hasher.Hash; // write the hash to the end of the file cout.Write(hash, 0, hash.Length); // mout.Write(hash,0,hash.Length); // flush and close the cryptostream cout.Flush(); cout.FlushFinalBlock(); // cout.Close(); // mout.Flush(); // mout.Close(); return(mout); } } }
/// <summary> /// takes an input file and decrypts it to the output file /// </summary> /// <param name="inputFilePath">the file to decrypt</param> /// <param name="outputFilePath">the to write the decrypted data to</param> /// <param name="password">the password used as the key</param> /// <param name="callback">the method to call to notify of progress</param> public static DecryptionResult TryDecryptFile(string inputFilePath, string outputFilePath, string password, CryptoProgressCallBack callback) { using (FileStream inputStream = File.OpenRead(inputFilePath)) { int orignalInputSize = (int)inputStream.Length; byte[] bytes = new byte[BUFFER_SIZE]; int numOutputBytesProcessed = 0; // read off the IV and Salt byte[] iv = new byte[16]; inputStream.Read(iv, 0, 16); byte[] salt = new byte[16]; inputStream.Read(salt, 0, 16); // create the crypting stream SymmetricAlgorithm sma = CreateRijndael(password, salt); sma.IV = iv; int numTotalBytesProcessed = 32; long encryptedStreamLength; // the size stored in the input stream // create the cryptostreams that will process the file using (CryptoStream inputCryptoStream = new CryptoStream(inputStream, sma.CreateDecryptor(), CryptoStreamMode.Read)) { using (var bReader = new BinaryReader(inputCryptoStream)) { encryptedStreamLength = bReader.ReadInt64(); ulong tag = bReader.ReadUInt64(); if (FC_TAG != tag) { return(DecryptionResult.FailedFileCorrupted); } // Create the hash algorithm object. This will be generated as we output the encrypted // file and it can then be compared against the original has appended to the file using (HashAlgorithm workingHashAlgorithm = SHA256.Create()) { using ( CryptoStream hashCryptoStream = new CryptoStream(Stream.Null, workingHashAlgorithm, CryptoStreamMode.Write)) { using (FileStream outputStream = File.OpenWrite(outputFilePath)) { #region Decrypt and output // Determine number of reads required to loop through the input stream long numReads = encryptedStreamLength / BUFFER_SIZE; for (int i = 0; i < numReads; ++i) { int numBytesRead = inputCryptoStream.Read(bytes, 0, bytes.Length); outputStream.Write(bytes, 0, numBytesRead); hashCryptoStream.Write(bytes, 0, numBytesRead); numTotalBytesProcessed += numBytesRead; numOutputBytesProcessed += numBytesRead; if (callback != null) { callback(0, orignalInputSize, numTotalBytesProcessed); } } // Calculate remaining bytes of stream long remainingBytes = encryptedStreamLength % BUFFER_SIZE; if (remainingBytes > 0) { int numBytesRead = inputCryptoStream.Read(bytes, 0, (int)remainingBytes); outputStream.Write(bytes, 0, numBytesRead); hashCryptoStream.Write(bytes, 0, numBytesRead); numTotalBytesProcessed += numBytesRead; numOutputBytesProcessed += numBytesRead; if (callback != null) { callback(0, orignalInputSize, numTotalBytesProcessed); } } #endregion } } byte[] hashGeneratedFromDecryption = workingHashAlgorithm.Hash; // Get and compare the current and old hash values byte[] hashExtractedFromInputFile = new byte[workingHashAlgorithm.HashSize / 8]; int hashLength = inputCryptoStream.Read(hashExtractedFromInputFile, 0, hashExtractedFromInputFile.Length); if ((hashExtractedFromInputFile.Length != hashLength) || (!CheckByteArrays(hashExtractedFromInputFile, hashGeneratedFromDecryption))) { return(DecryptionResult.FailedHashesDoNotMatch); } } } } if (numOutputBytesProcessed != encryptedStreamLength) { return(DecryptionResult.FailedFileSizesDoNotMatch); } } return(DecryptionResult.Success); }
/// <summary> /// This takes an input file and encrypts it into the output file /// </summary> /// <param name="inputFilePath">the file to encrypt</param> /// <param name="outputFilePath">the file to write the encrypted data to</param> /// <param name="password">the password for use as the key</param> /// <param name="callback">the method to call to notify of progress</param> public static void EncryptFile(string inputFilePath, string outputFilePath, string password, CryptoProgressCallBack callback) { DoEncryption(inputFilePath, outputFilePath, password, callback); }
private static void DoEncryption(string inputFilePath, string outputFilePath, string password, CryptoProgressCallBack callback) { using (FileStream inputStream = File.OpenRead(inputFilePath), outputStream = File.OpenWrite(outputFilePath)) { long inputSize = inputStream.Length; int workingSize = (int)inputSize; byte[] bytes = new byte[BUFFER_SIZE]; int processedSize = 0; // Create salt and IV byte[] iv = GenerateRandomBytes(16); byte[] salt = GenerateRandomBytes(16); // Write the IV and salt values to the beginning of the output stream outputStream.Write(iv, 0, iv.Length); outputStream.Write(salt, 0, salt.Length); // Create the crypting object SymmetricAlgorithm sma = CreateRijndael(password, salt); sma.IV = iv; // Create the hashing and crypto streams HashAlgorithm hashAlgorithm = SHA256.Create(); using (CryptoStream outputCryptoStream = new CryptoStream(outputStream, sma.CreateEncryptor(), CryptoStreamMode.Write)) { // Write the size of the file and the // crypto tag to the output file using (BinaryWriter bWriter = new BinaryWriter(outputCryptoStream)) { bWriter.Write(inputSize); bWriter.Write(FC_TAG); using (CryptoStream hashCryptoStream = new CryptoStream(Stream.Null, hashAlgorithm, CryptoStreamMode.Write)) { int bytesRead; while ((bytesRead = inputStream.Read(bytes, 0, bytes.Length)) != 0) { outputCryptoStream.Write(bytes, 0, bytesRead); hashCryptoStream.Write(bytes, 0, bytesRead); processedSize += bytesRead; if (callback != null) { callback(0, workingSize, processedSize); } } } // read the hash byte[] hash = hashAlgorithm.Hash; // write the hash to the end of the file outputCryptoStream.Write(hash, 0, hash.Length); } } } }