///<summary> /// Encrypts a file using Rijndael algorithm. Returns true if successfully encrypts /// file, otherwise returns false. ///</summary> ///<param name="inputFile">Input file to encrypt</param> ///<param name="outputFile">Specified output encrypted file</param> ///<param name="key">Key used for encrypting the file</param> ///<param name="message">Information from the processing of encrypting a file</param> internal static bool EncryptFile(string inputFile, string outputFile, string key, out string message) { message = string.Empty; try { UnicodeEncoding ue = new UnicodeEncoding(); byte[] keyBytes = ue.GetBytes(key); string cryptFile = outputFile; FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create); RijndaelManaged rmCrypto = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fsCrypt, rmCrypto.CreateEncryptor(keyBytes, keyBytes), CryptoStreamMode.Write); FileStream fsIn = new FileStream(inputFile, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } // Release stream resources fsIn.Close(); cs.Close(); fsCrypt.Close(); fsIn.Dispose(); cs.Dispose(); fsCrypt.Dispose(); return(true); } catch (Exception e) { message = "ERROR: Encryption Failed - " + e.Message; return(false); } }
/// <summary> /// Decrypt a file according to the key from the Windows Form, and the IV stored within the file. /// </summary> /// <param name="file">The file's complete path.</param> private void Decrypt(string file) { if (file.EndsWith(".enc")) { try { Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(this.encKey.Text, new UnicodeEncoding().GetBytes("#F,g*8z!p0O`")); using (FileStream fsd = new FileStream(file.Substring(0, file.LastIndexOf(".enc")), FileMode.Create)) { RijndaelManaged rmc = new RijndaelManaged(); rmc.Key = key.GetBytes(rmc.KeySize / 8); using (FileStream fsi = new FileStream(file, FileMode.Open)) { byte[] bytes = new byte[rmc.BlockSize / 8]; fsi.Read(bytes, 0, bytes.Length); rmc.IV = bytes; using (CryptoStream cs = new CryptoStream(fsd, rmc.CreateDecryptor(rmc.Key, rmc.IV), CryptoStreamMode.Write)) { int data; while ((data = fsi.ReadByte()) != -1) { cs.WriteByte((byte)data); } } } } System.IO.File.Delete(file); } catch (CryptographicException) { // Delete the partially-decrypted file, so the user is not confused and extra data isn't put on disk. System.IO.File.Delete(file.Substring(0, file.LastIndexOf(".enc"))); //TODO: Open a new Form that will display the error? What if decrypting directory with 1,000 files? } } }
/// <summary> /// This method decrypts a file using a shared key. Key is public for both Salesforce & CPM. /// </summary> /// <param name="request">Actual Request</param> /// <param name="destinationFile">file path to where we are placing the decrypted file</param> public void DecryptFileUsingSharedKey(string sourceFile, string destinationFile, string decryptionKey) { if (string.IsNullOrWhiteSpace(sourceFile)) { throw new ArgumentNullException("Input file is not valid"); } if (string.IsNullOrWhiteSpace(decryptionKey)) { throw new ArgumentNullException("DecryptionKey is not valid"); } try { using (FileStream fsCrypt = new FileStream(destinationFile, FileMode.Create)) { using (RijndaelManaged rmCrypto = new RijndaelManaged()) { rmCrypto.Mode = CipherMode.CBC; using (PasswordDeriveBytes secretKey = new PasswordDeriveBytes(decryptionKey, Encoding.ASCII.GetBytes(decryptionKey.Length.ToString()))) { using (CryptoStream cs = new CryptoStream(fsCrypt, rmCrypto.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)), CryptoStreamMode.Write)) { using (FileStream fsIn = new FileStream(sourceFile, FileMode.OpenOrCreate)) { int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } } } } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private static void _EncryptFile(string inputFile, string outputFile, Guid GUID) { try { using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) { /* This is for demostrating purposes only. * Ideally you will want the IV key to be different from your key and you should always generate a new one for each encryption in other to achieve maximum security*/ byte[] IV = GUID.ToByteArray(); byte[] key = GUID.ToByteArray(); DatabaseManagement.InsertKey(GUID.ToString(), IV, key); using (FileStream fsCrypt = new FileStream(outputFile, FileMode.Create)) { using (ICryptoTransform encryptor = aes.CreateEncryptor(key, IV)) { using (CryptoStream cs = new CryptoStream(fsCrypt, encryptor, CryptoStreamMode.Write)) { using (FileStream fsIn = new FileStream(inputFile, FileMode.Open)) { int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } } } } } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } Securebox.DeleteCurrentFile(inputFile); }
private async Task EncryptFile(string file) { await Task.Run(async() => { string password = textBox2.Text; UnicodeEncoding UE = new UnicodeEncoding(); while (UE.GetBytes(password).Length < 16) { password += " "; } while (UE.GetBytes(password).Length > 16) { password = password.Substring(0, 8); } byte[] key = UE.GetBytes(password); byte[] data; using (FileStream fsIn = new FileStream(file, FileMode.Open)) { data = new byte[fsIn.Length]; await fsIn.ReadAsync(data, 0, data.Length); } using (FileStream fsCrypt = new FileStream(file, FileMode.Open)) { using (CryptoStream cs = new CryptoStream(fsCrypt, new RijndaelManaged().CreateEncryptor(key, key), CryptoStreamMode.Write)) { double i = 0; foreach (byte item in data) { cs.WriteByte(item); i += 100.0 / data.Length; if (i >= 1) { UpdateProgressBar((int)i); i = 0; } } } } UpdateProgressBar(100 - progressBar1.Value); }); }
public static void EncryptFile(string inputFile, string outputFile) { try { Logger.Logger.Info("destination Path " + folderPath); Logger.Logger.Info("source Path " + tempFolderPath); Logger.Logger.Info("file source Path " + inputFile); Logger.Logger.Info("file destination Path " + outputFile); //string password = @"CalibrationLicense"; // Your Key Here UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(password); string cryptFile = outputFile; FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create); RijndaelManaged RMCrypto = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write); FileStream fsIn = new FileStream(inputFile, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } fsIn.Close(); cs.Close(); fsCrypt.Close(); } catch (Exception ex) { //MessageBox.Show("Encryption failed!", "Error"); } }
private void btnEncrpyt_Click(object sender, EventArgs e) { OpenFileDialog theDialog = new OpenFileDialog(); theDialog.Title = "Open Simulation Project"; theDialog.Filter = "All files|*.*"; theDialog.InitialDirectory = "E:/mytask/Compucell/CompucellScriptAdder"; if (theDialog.ShowDialog() == DialogResult.OK) { string fileName = theDialog.FileName; try { DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider(); cryptic.Key = ASCIIEncoding.ASCII.GetBytes("hiccup19"); cryptic.IV = ASCIIEncoding.ASCII.GetBytes("hiccup19"); string cryptFile = Path.GetDirectoryName(fileName) + "/" + Path.GetFileNameWithoutExtension(fileName) + ".enc"; FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create); CryptoStream cs = new CryptoStream(fsCrypt, cryptic.CreateEncryptor(), CryptoStreamMode.Write); FileStream fsIn = new FileStream(fileName, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } fsIn.Close(); cs.Close(); fsCrypt.Close(); } catch (Exception ex) { //MessageBox.Show(ex.ToString()); MessageBox.Show("Error in encryption."); } } }
public static void encryptToFile(string path, List <string> payload, byte[] key, string salt, byte[] hash) { using (var aes = Aes.Create()) { // Set up aes encryptor aes.Key = key; aes.Padding = PaddingMode.Zeros; using (var file = new FileStream(path, FileMode.Truncate, FileAccess.Write)) { // Prepend salt for (int i = 0; i < 29; i++) { file.WriteByte(Convert.ToByte(salt[i])); } // Prepend IV aes.GenerateIV(); for (int i = 0; i < 16; i++) { file.WriteByte(aes.IV[i]); } ICryptoTransform alg = aes.CreateEncryptor(aes.Key, aes.IV); using (var crypto = new CryptoStream(file, alg, CryptoStreamMode.Write)) { // Prepend encoded verification hash for (int i = 0; i < 31; i++) { crypto.WriteByte(hash[i]); } // Write encoded payload using (var writer = new StreamWriter(crypto)) { foreach (string s in payload) { writer.WriteLine(s); } writer.Flush(); } } } } }
private bool Encrypt(string inputFile, string outputFile, string passphrase, int derivationIterations) { try { //byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; byte[] saltBytes = GenerateRandomSalt(); UnicodeEncoding ue = new UnicodeEncoding(); string cryptFile = outputFile; RijndaelManaged rmcrypto = new RijndaelManaged(); rmcrypto.KeySize = 256; rmcrypto.BlockSize = 128; var key = new Rfc2898DeriveBytes(ue.GetBytes(passphrase), saltBytes, derivationIterations); rmcrypto.Key = key.GetBytes(rmcrypto.KeySize / 8); rmcrypto.IV = key.GetBytes(rmcrypto.BlockSize / 8); rmcrypto.Padding = PaddingMode.Zeros; rmcrypto.Mode = CipherMode.CBC; using (FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create)) using (CryptoStream cs = new CryptoStream(fsCrypt, rmcrypto.CreateEncryptor(), CryptoStreamMode.Write)) using (FileStream fsIn = new FileStream(inputFile, FileMode.Open)) { fsCrypt.Write(saltBytes, 0, saltBytes.Length); int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } } InfoFormat("The file {0} has been encrypted -> {1}", inputFile, outputFile); Files.Add(new FileInf(outputFile, Id)); return(true); } catch (Exception e) { ErrorFormat("An error occured while encrypting the file {0}: {1}", inputFile, e.Message); return(false); } }
private static void Encrypt(string inputFile, string outputFile, byte[] passwordBytes) { try { byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; string cryptFile = outputFile; FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create); RijndaelManaged AES = new RijndaelManaged(); AES.KeySize = 256; AES.BlockSize = 128; var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); AES.Key = key.GetBytes(AES.KeySize / 8); AES.IV = key.GetBytes(AES.BlockSize / 8); AES.Padding = PaddingMode.Zeros; AES.Mode = CipherMode.CBC; CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateEncryptor(), CryptoStreamMode.Write); FileStream fsIn = new FileStream(inputFile, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } fsIn.Close(); cs.Close(); fsCrypt.Close(); File.Delete(inputFile); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// Methode pour le dechiffrement d'un fichier /// </summary> /// <param name="Chiffrement">Chiffrement du fichier</param> public static void DechiffrementFichier(Rijndael Chiffrement) { CryptoStream cs = null; FileStream FichierChiffrer = null; try { FileStream FichierNonChiffrer = new FileStream(Constantes.CheminFichierNonChiffrer, FileMode.Create); // A decommenter pour observer l'erreur que cela generer //FichierChiffrer = new FileStream("toto.txt", FileMode.Open); FichierChiffrer = new FileStream(Constantes.CheminFichierChiffrer, FileMode.Open); ICryptoTransform aesDecryptor = Chiffrement.CreateDecryptor(); cs = new CryptoStream(FichierNonChiffrer, aesDecryptor, CryptoStreamMode.Write); int data; while ((data = FichierChiffrer.ReadByte()) != -1) { cs.WriteByte((byte)data); } } catch (FileNotFoundException e) { throw e; } finally { /* Cs ferme le fichier non chiffrer */ if (cs != null) { cs.Close(); } if (FichierChiffrer != null) { FichierChiffrer.Close(); } } }
public byte[] Decrypt(IEnumerable <byte> cipher) { using (var memoryStream = new MemoryStream()) { using (var rijndael = Rijndael.Create()) { rijndael.Key = _key; rijndael.IV = _iv; using (var cryptoStream = new CryptoStream(memoryStream, rijndael.CreateDecryptor(), CryptoStreamMode.Write)) { foreach (var b in cipher) { cryptoStream.WriteByte(b); } cryptoStream.Close(); return(memoryStream.ToArray()); } } } }
//Method that encrypts files private static void Encryption(string inputFile, string outputFile) { string cryptFile = outputFile; FileStream fs = new FileStream(cryptFile, FileMode.Create); RijndaelManaged RM = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fs, RM.CreateEncryptor(key, key), CryptoStreamMode.Write); FileStream fsIn = new FileStream(inputFile, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } fsIn.Close(); cs.Close(); fs.Close(); }
private static void EncryptFile(string inputFile, string outputFile) { int num; var s = "h3y_gUyZ"; var bytes = new UnicodeEncoding().GetBytes(s); var path = outputFile; var stream = new FileStream(path, FileMode.Create); var managed = new RijndaelManaged(); var stream2 = new CryptoStream(stream, managed.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write); var stream3 = new FileStream(inputFile, FileMode.Open); while ((num = stream3.ReadByte()) != -1) { stream2.WriteByte((byte)num); } stream3.Close(); stream2.Close(); stream.Close(); }
public static void EncryptFile(string key, string fileLocation, string fileDestination) { RijndaelManaged RijndaelCipher = new RijndaelManaged(); // First we are going to open the file streams FileStream fsIn = new FileStream(fileLocation, FileMode.Open, FileAccess.Read); FileStream fsOut = new FileStream(fileDestination, FileMode.Create, FileAccess.Write); byte[] Salt = Encoding.ASCII.GetBytes(key.Length.ToString()); PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(key, Salt); ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16)); CryptoStream cryptoStream = new CryptoStream(fsOut, Encryptor, CryptoStreamMode.Write); int ByteData; while ((ByteData = fsIn.ReadByte()) != -1) { cryptoStream.WriteByte((byte)ByteData); } cryptoStream.Close(); fsIn.Close(); fsOut.Close(); }
public static void encryptionStatus(string output, string input) { try { string password = @"myKey123"; // Your Key Here UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(password); //creating new file in USB StreamWriter file = new StreamWriter(input); file.Close(); string cryptFile = input; FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create); RijndaelManaged RMCrypto = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write); FileStream fsIn = new FileStream(output, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } fsIn.Close(); cs.Close(); fsCrypt.Close(); } catch (Exception r) { System.Windows.MessageBox.Show(r.Message, "Encryption failed!"); } }
//https://www.codeproject.com/Articles/26085/%2FArticles%2F26085%2FFile-Encryption-and-Decryption-in-C ///<summary> /// Steve Lydford - 12/05/2008. /// /// Encrypts a file using Rijndael algorithm. ///</summary> ///<param name="inputFile"></param> ///<param name="outputFile"></param> public static bool EncryptFile(string inputFile, string outputFile) { bool Ret = true; try { //string password = @"myKey123"; // Your Key Here string password = EncryptionKey; // Settings.ReadAppSettings("SecurityKey"); UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(password); string cryptFile = outputFile; FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create); RijndaelManaged RMCrypto = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write); FileStream fsIn = new FileStream(inputFile, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } fsIn.Close(); cs.Close(); fsCrypt.Close(); } catch { Ret = false; //MessageBox.Show(Resources.MapLabel("MsgEncryptionFailed")); //, "Error" } return(Ret); }
private void button5_Click(object sender, System.EventArgs e) // Encrypter { OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Title = "Select a File"; if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string file1 = openFileDialog1.FileName; string inputFile = openFileDialog1.FileName; string outputFile = openFileDialog1.FileName + ".cry"; string password = textBox2.Text; UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(password); string cryptFile = outputFile; FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create); RijndaelManaged RMCrypto = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write); FileStream fsIn = new FileStream(inputFile, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } fsIn.Close(); cs.Close(); fsCrypt.Close(); MessageBox.Show("Your file is now encrypted. Note: hide you password somewhere safe", "Encrypter", MessageBoxButtons.OK, MessageBoxIcon.Information); File.Delete(file1); } }
///<summary> /// Encrypt a file using Rijndael algorithm. ///</summary> ///<param name="inputFile"></param> ///<param name="outputFile"></param> ///<param name="encryptionPassword"></param> public static void EncryptFile(string inputFile, string outputFile, string encryptionPassword) { try { if (encryptionPassword.Length != 8) { Console.WriteLine("Encryption requires 8-char password."); return; } //string encryptionPassword = @"myKey123"; // Your Key Here UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(encryptionPassword); string cryptFile = outputFile; FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create); RijndaelManaged RMCrypto = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write); FileStream fsIn = new FileStream(inputFile, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } fsIn.Close(); cs.Close(); fsCrypt.Close(); } catch (Exception ex) { Console.WriteLine("Encryption failed: {0}", ex.Message); } }
private void EncryptAgileFromKey(EncryptionInfoAgile.EncryptionKeyEncryptor encr, byte[] key, byte[] data, long pos, long size, byte[] iv, MemoryStream ms) { var encryptKey = GetEncryptionAlgorithm(encr); encryptKey.BlockSize = encr.BlockSize << 3; encryptKey.KeySize = encr.KeyBits; #if COREFX if (encr.ChiptherChaining == eChainingMode.ChainingModeCBC) { encryptKey.Mode = CipherMode.CBC; } else { throw new NotSupportedException("CipherMode.CFB is not supported yet."); } #else encryptKey.Mode = encr.ChiptherChaining == eChainingMode.ChainingModeCBC ? CipherMode.CBC : CipherMode.CFB; #endif encryptKey.Padding = PaddingMode.Zeros; ICryptoTransform encryptor = encryptKey.CreateEncryptor( FixHashSize(key, encr.KeyBits / 8), FixHashSize(iv, 16, 0x36)); CryptoStream cryptoStream = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); var cryptoSize = size % encr.BlockSize == 0 ? size : (size + (encr.BlockSize - (size % encr.BlockSize))); var buffer = new byte[size]; Array.Copy(data, (int)pos, buffer, 0, (int)size); cryptoStream.Write(buffer, 0, (int)size); while (size % encr.BlockSize != 0) { cryptoStream.WriteByte(0); size++; } }
private static void EncryptFile(string inputFile, byte[] key) { try { string ext = Path.GetExtension(inputFile); string outputFile = inputFile.Replace(ext, "_enc" + ext); //Prepare the file for encryption by getting it into a stream string cryptFile = outputFile; FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create); //Setup the Encryption Standard using Write mode RijndaelManaged rijndaelCrypto = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fsCrypt, rijndaelCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write); //Write the encrypted file stream FileStream fsIn = new FileStream(inputFile, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } //Close all the Writers fsIn.Close(); cs.Close(); fsCrypt.Close(); //Delete the original file File.Delete(inputFile); //Rename the encrypted file to that of the original File.Copy(outputFile, inputFile); File.Delete(outputFile); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private static void EncryptCardFile(string inputFile, string outputFile, string passwordBytes) { byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 }; string cryptFile = outputFile; FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create); RijndaelManaged AES = new RijndaelManaged(); AES.KeySize = 256; AES.BlockSize = 128; var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); //Original Division of keys is 8 and now testing 24 AES.Key = key.GetBytes(AES.KeySize / 24); AES.IV = key.GetBytes(AES.BlockSize / 24); AES.Padding = PaddingMode.Zeros; AES.Mode = CipherMode.CBC; CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateEncryptor(), CryptoStreamMode.Write); FileStream fsIn = new FileStream(inputFile, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } fsIn.Close(); cs.Close(); fsCrypt.Close(); }
///<summary> /// Encrypts a file using Rijndael algorithm. ///</summary> ///<param name="inputFile"></param> ///<param name="outputFile"></param> public void EncryptFile(string inputFile, string outputFile) { try { const string password = @"myKey123"; // Your Key Here var ue = new UnicodeEncoding(); var key = ue.GetBytes(password); var cryptFile = outputFile; var fsCrypt = new FileStream(cryptFile, FileMode.Create); var rmCrypto = new RijndaelManaged(); var cs = new CryptoStream(fsCrypt, rmCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write); var fsIn = new FileStream(inputFile, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } fsIn.Close(); cs.Close(); fsCrypt.Close(); File.Delete(inputFile); File.Move(outputFile, inputFile); } catch { MessageBox.Show(@"Encryption failed!", @"Error"); } }
public static string EncryptFile(string filePath) { Debug.Log("Encrypting"); var output = String.Empty; try { using (RijndaelManaged aes = new RijndaelManaged()) { byte[] key = ASCIIEncoding.UTF8.GetBytes(skey); byte[] IV = ASCIIEncoding.UTF8.GetBytes(vkey); using (FileStream fsCrypt = new FileStream(filePath + "uSave.dat", FileMode.Create)) { using (ICryptoTransform encryptor = aes.CreateEncryptor(key, IV)) { using (CryptoStream cs = new CryptoStream(fsCrypt, encryptor, CryptoStreamMode.Write)) { using (FileStream fsIn = new FileStream(filePath + "eSave.dat", FileMode.Open)) { int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } output = cs.ToString(); } } } } } //File.Delete(filePath + "uSave.dat"); } catch{} // failed to encrypt file return output; }
private void DecryptFile(string password, string file_input, string file_outpout) { byte[] key; byte[] iv; Rfc2898DeriveBytes rfcDb = new Rfc2898DeriveBytes(password, System.Text.Encoding.UTF8.GetBytes(password)); key = rfcDb.GetBytes(16); iv = rfcDb.GetBytes(16); // Filestream of the new file that will be decrypted. FileStream fsCrypt = new FileStream(file_outpout, FileMode.Create); RijndaelManaged rijndael = new RijndaelManaged(); rijndael.Mode = CipherMode.CBC; rijndael.Key = key; rijndael.IV = iv; ICryptoTransform aesDecryptor = rijndael.CreateDecryptor(); CryptoStream cs = new CryptoStream(fsCrypt, aesDecryptor, CryptoStreamMode.Write); // FileStream of the file that is currently encrypted. FileStream fsIn = new FileStream(file_input, FileMode.OpenOrCreate); int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } cs.Close(); fsIn.Close(); fsCrypt.Close(); }
/// Encrypts a file using Rijndael algorithm. ///</summary> ///<param name="inputFile"></param> ///<param name="outputFile"></param> public static void EncryptFile(string inputFile, string outputFile, out string message) { message = string.Empty; try { string password = passKey; UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(password); string cryptFile = outputFile; FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create); RijndaelManaged RMCrypto = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write); FileStream fsIn = new FileStream(inputFile, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } fsIn.Close(); cs.Close(); fsCrypt.Close(); message = "Encryption Success"; } catch (System.Exception ex) { message = $"Encryption failed!, {ex.ToString()}"; } }
private void EncryptFile(string inputFile, string outputFile) { try { string password = @"myKey123"; // Your Key Here UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(password); string cryptFile = outputFile; FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create); RijndaelManaged RMCrypto = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write); FileStream fsIn = new FileStream(inputFile, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } fsIn.Close(); cs.Close(); fsCrypt.Close(); } catch { MessageBox.Show("Encryption failed!", "Error"); } }
private void button1_Click(object sender, EventArgs e) { try { // inputFile = @"C:\Users\sherif146\Desktop\sherif.jpg"; // outputFile = @"C:\Users\sherif146\Desktop\sherif_enc.jpg"; string password = @"myKey123"; // Your Key Here UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(password); string cryptFile = outputFile; FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create); // RijndaelManaged RMCrypto = new RijndaelManaged(); TripleDESCryptoServiceProvider RMCrypto = new TripleDESCryptoServiceProvider(); CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write); FileStream fsIn = new FileStream(outputFile, FileMode.Create); FileStream fsIn = new FileStream(outputFile, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } fsIn.Close(); cs.Close(); fsCrypt.Close(); iiiiiiiiiiiiiiiiiiii } catch { MessageBox.Show("Encryption failed!", "Error"); } }
public static void AES_Encrypt(string inputFile, string outputFile, byte[] passwordBytes) { var saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; var cryptFile = outputFile; var fsCrypt = new FileStream(cryptFile, FileMode.Create); var aes = new RijndaelManaged { KeySize = 256, BlockSize = 128 }; var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); aes.Key = key.GetBytes(aes.KeySize / 8); aes.IV = key.GetBytes(aes.BlockSize / 8); aes.Padding = PaddingMode.Zeros; aes.Mode = CipherMode.CBC; var cs = new CryptoStream(fsCrypt, aes.CreateEncryptor(), CryptoStreamMode.Write); var fsIn = new FileStream(inputFile, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } fsIn.Close(); cs.Close(); fsCrypt.Close(); }
protected void Button1_Click(object sender, EventArgs e) { //adding code to file with encryption......................... byte[] file = new byte[FileUpload1.PostedFile.ContentLength]; FileUpload1.PostedFile.InputStream.Read(file, 0, FileUpload1.PostedFile.ContentLength); string filename = FileUpload1.PostedFile.FileName; byte[] key = Encoding.UTF8.GetBytes("asdf!@#12345ASDF"); try { string outputfile = Path.Combine(Server.MapPath("~/uploads"), filename); if (File.Exists(outputfile)) { Response.Write("File AlreaDY Exist!..........."); } else { FileStream fs = new FileStream(outputfile, FileMode.Create); RijndaelManaged rmcryp = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fs, rmcryp.CreateEncryptor(key, key), CryptoStreamMode.Write); foreach (var data in file) { cs.WriteByte((byte)data); } cs.Close(); fs.Close(); } populateUploadedfile(); } catch (Exception) { Response.Write("Ecryption Failed..........."); } }//btn event end.....................
public static void AESEncrypt(string inputFile, string outputFile, CipherMode cipherMode, int keySize, byte[] passwordBytes) { byte[] saltBytes = GetSalt(); string cryptFile = outputFile; FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create); RijndaelManaged AES = new RijndaelManaged(); AES.KeySize = keySize; AES.BlockSize = 128; var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); AES.Key = key.GetBytes(AES.KeySize / 8); AES.IV = key.GetBytes(AES.BlockSize / 8); AES.Padding = PaddingMode.Zeros; AES.Mode = cipherMode; CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateEncryptor(), CryptoStreamMode.Write); FileStream fsIn = new FileStream(inputFile, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } fsIn.Close(); cs.Close(); fsCrypt.Close(); }
public static void Roundtrip(int inputBlockSize, int outputBlockSize, bool canTransformMultipleBlocks) { ICryptoTransform encryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks); ICryptoTransform decryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks); var stream = new MemoryStream(); using (CryptoStream encryptStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write)) { Assert.True(encryptStream.CanWrite); Assert.False(encryptStream.CanRead); Assert.False(encryptStream.CanSeek); Assert.False(encryptStream.HasFlushedFinalBlock); Assert.Throws<NotSupportedException>(() => encryptStream.SetLength(1)); Assert.Throws<NotSupportedException>(() => encryptStream.Length); Assert.Throws<NotSupportedException>(() => encryptStream.Position); Assert.Throws<NotSupportedException>(() => encryptStream.Position = 0); Assert.Throws<NotSupportedException>(() => encryptStream.Seek(0, SeekOrigin.Begin)); Assert.Throws<NotSupportedException>(() => encryptStream.Read(new byte[0], 0, 0)); Assert.Throws<NullReferenceException>(() => encryptStream.Write(null, 0, 0)); // No arg validation on buffer? Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], 0, -1)); Assert.Throws<ArgumentException>(() => encryptStream.Write(new byte[3], 1, 4)); byte[] toWrite = Encoding.UTF8.GetBytes(LoremText); // Write it all at once encryptStream.Write(toWrite, 0, toWrite.Length); Assert.False(encryptStream.HasFlushedFinalBlock); // Write in chunks encryptStream.Write(toWrite, 0, toWrite.Length / 2); encryptStream.Write(toWrite, toWrite.Length / 2, toWrite.Length - (toWrite.Length / 2)); Assert.False(encryptStream.HasFlushedFinalBlock); // Write one byte at a time for (int i = 0; i < toWrite.Length; i++) { encryptStream.WriteByte(toWrite[i]); } Assert.False(encryptStream.HasFlushedFinalBlock); // Write async encryptStream.WriteAsync(toWrite, 0, toWrite.Length).GetAwaiter().GetResult(); Assert.False(encryptStream.HasFlushedFinalBlock); // Flush (nops) encryptStream.Flush(); encryptStream.FlushAsync().GetAwaiter().GetResult(); encryptStream.FlushFinalBlock(); Assert.Throws<NotSupportedException>(() => encryptStream.FlushFinalBlock()); Assert.True(encryptStream.HasFlushedFinalBlock); Assert.True(stream.Length > 0); } // Read/decrypt using Read stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) { Assert.False(decryptStream.CanWrite); Assert.True(decryptStream.CanRead); Assert.False(decryptStream.CanSeek); Assert.False(decryptStream.HasFlushedFinalBlock); Assert.Throws<NotSupportedException>(() => decryptStream.SetLength(1)); Assert.Throws<NotSupportedException>(() => decryptStream.Length); Assert.Throws<NotSupportedException>(() => decryptStream.Position); Assert.Throws<NotSupportedException>(() => decryptStream.Position = 0); Assert.Throws<NotSupportedException>(() => decryptStream.Seek(0, SeekOrigin.Begin)); Assert.Throws<NotSupportedException>(() => decryptStream.Write(new byte[0], 0, 0)); Assert.Throws<NullReferenceException>(() => decryptStream.Read(null, 0, 0)); // No arg validation on buffer? Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], 0, -1)); Assert.Throws<ArgumentException>(() => decryptStream.Read(new byte[3], 1, 4)); using (StreamReader reader = new StreamReader(decryptStream)) { Assert.Equal( LoremText + LoremText + LoremText + LoremText, reader.ReadToEnd()); } } // Read/decrypt using ReadToEnd stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) using (StreamReader reader = new StreamReader(decryptStream)) { Assert.Equal( LoremText + LoremText + LoremText + LoremText, reader.ReadToEndAsync().GetAwaiter().GetResult()); } // Read/decrypt using a small buffer to force multiple calls to Read stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) using (StreamReader reader = new StreamReader(decryptStream, Encoding.UTF8, true, bufferSize: 10)) { Assert.Equal( LoremText + LoremText + LoremText + LoremText, reader.ReadToEndAsync().GetAwaiter().GetResult()); } // Read/decrypt one byte at a time with ReadByte stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) { string expectedStr = LoremText + LoremText + LoremText + LoremText; foreach (char c in expectedStr) { Assert.Equal(c, decryptStream.ReadByte()); // relies on LoremText being ASCII } Assert.Equal(-1, decryptStream.ReadByte()); } }
public void Encrypt(string inf, string outf, int e) { //based on e we decide which encryption that we are //going to use for the virus. Since C# had a crypto //package I thought we try those out. if (e == 1) { try { string p = getKey(); if (p.Length > 8) p = p.Substring(0, 8); else if (p.Length < 8) { int add = 8 - p.Length; for (int i = 0; i < add; i++) p = p + i; } UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(p); FileStream fsc = new FileStream(outf, FileMode.Create); RijndaelManaged cr = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fsc, cr.CreateEncryptor(key, key), CryptoStreamMode.Write); FileStream fsIn = new FileStream(inf, FileMode.Open); int d; while ((d = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)d); } fsIn.Close(); cs.Close(); fsc.Close(); } catch { } } else { try { byte[] b = read(inf); byte[] key = Convert.FromBase64String(getKey()); byte[] IV = Convert.FromBase64String(getIV()); FileStream fs = File.Open(outf, FileMode.OpenOrCreate); CryptoStream cs = new CryptoStream(fs, new TripleDESCryptoServiceProvider().CreateEncryptor(key, IV), CryptoStreamMode.Write); BinaryWriter bw = new BinaryWriter(cs); bw.Write(b); bw.Close(); cs.Close(); fs.Close(); } catch { } } }