WriteByte() public method

public WriteByte ( byte value ) : void
value byte
return void
        public static void DecryptFile(string strKey, string pathCypheredTextFile, string pathPlainTextFile)
        {
            // Place la clé de déchiffrement dans un tableau d'octets
            byte[] key = GenerateAlgotihmInputs(strKey);

            // Place le vecteur d'initialisation dans un tableau d'octets
            byte[] iv = GenerateAlgotihmInputs(strKey);

            // Filestream of the new file that will be decrypted.
            Directory.CreateDirectory(Directory.GetParent(pathPlainTextFile).FullName);
            FileStream fsCrypt = new FileStream(pathPlainTextFile, 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(pathCypheredTextFile, FileMode.OpenOrCreate);

            int data;

            while ((data = fsIn.ReadByte()) != -1)
                cs.WriteByte((byte)data);
            cs.Close();
            fsIn.Close();
            fsCrypt.Close();
        }
 public void EncryptFile(string inputFile, string outputFile, string securityKey)
 {
     try
     {
         using (RijndaelManaged aes = new RijndaelManaged())
         {
             byte[] key = ASCIIEncoding.UTF8.GetBytes(securityKey);
             byte[] IV = ASCIIEncoding.UTF8.GetBytes("1234567890qwerty");
             //aes.Padding = PaddingMode.None;
             using (FileStream fsCrypt = new FileStream(outputFile, FileMode.Create))
             {
                 Console.WriteLine("File created.");
                 using (ICryptoTransform encryptor = aes.CreateEncryptor(key, IV))
                 {
                     Console.WriteLine("Encrypt mode initiated.");
                     using (CryptoStream cs = new CryptoStream(fsCrypt, encryptor, CryptoStreamMode.Write))
                     {
                         Console.WriteLine("Encrypt stream initiated.");
                         using (FileStream fsIn = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
                         {
                             int data;
                             while ((data = fsIn.ReadByte()) != -1)
                             {
                                 cs.WriteByte((byte)data);
                             }
                             Console.WriteLine("File encrypted.");
                         }
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("This exception was caught: " + ex.ToString());
     }
 }
        ///<summary>
        /// Encrypts a file using Rijndael algorithm.
        ///</summary>
        ///<param name="inputFile"></param>
        ///<param name="outputFile"></param>
        public static void EncryptToFile(this string data, string outputFile, string password)
        {
            try
            {
                byte[] key = Encoding.UTF8.GetBytes(password);

                string cryptFile = outputFile;
                using (FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create))
                {
                    using (RijndaelManaged RMCrypto = new RijndaelManaged())
                    {
                        CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write);
                        using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(data)))
                        {
                            int datavar;
                            while ((datavar = ms.ReadByte()) != -1)
                                cs.WriteByte((byte)datavar);

                        }
                    }
                }
            }
            catch
            {
            }
        }
        public void encryption()
        {
            byte[] file = new byte[FileUpload1.PostedFile.ContentLength];
            FileUpload1.PostedFile.InputStream.Read(file, 0, FileUpload1.PostedFile.ContentLength);
            string fileName = txtfilename.Text;
            byte[] Key = Encoding.UTF8.GetBytes(LTRPRIKEY.Text);
            ASCIIEncoding.ASCII.GetString(Key);
            try
            {
                string outputFile = Path.Combine(Server.MapPath("~/uploadfiles/advance"), fileName);

                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();
                insert();


            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "popup",
                   "alert(" + ex + ");", true);
            }
        }
        public static void EncryptFile(string inputFile, string outputFile, string skey)
        {
            try
            {
                using (Aes aes = new AesManaged())
                {
                    var key = new Rfc2898DeriveBytes(skey, salt);

                    aes.Key = key.GetBytes(aes.KeySize / 8);
                    aes.IV = key.GetBytes(aes.BlockSize / 8);

                    using (FileStream fsCrypt = new FileStream(outputFile, FileMode.Create))
                    {
                        using (ICryptoTransform encryptor = aes.CreateEncryptor())
                        {
                            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 { throw; }
        }
Beispiel #6
0
        public static void Encrypt(string srcPath, string destPath, int salt, string encryptionKey)
        {
            DeriveBytes rgb = new Rfc2898DeriveBytes(encryptionKey, Encoding.Unicode.GetBytes(salt.ToString()));

            using (SymmetricAlgorithm aes = new RijndaelManaged())
            {
                aes.BlockSize = 128;
                aes.KeySize = 256;
                aes.Key = rgb.GetBytes(aes.KeySize >> 3);
                aes.IV = rgb.GetBytes(aes.BlockSize >> 3);
                aes.Mode = CipherMode.CBC;
                string key = "";
                string iv = "";
                using (FileStream fsCrypt = new FileStream(destPath, FileMode.Create))
                {
                    using (ICryptoTransform encryptor = aes.CreateEncryptor())
                    {
                        using (CryptoStream cs = new CryptoStream(fsCrypt, encryptor, CryptoStreamMode.Write))
                        {
                            using (FileStream fsIn = new FileStream(srcPath, FileMode.Open))
                            {
                                int data;
                                while ((data = fsIn.ReadByte()) != -1)
                                {
                                    cs.WriteByte((byte)data);
                                }
                            }
                        }
                    }
                }
            }
        }
Beispiel #7
0
        public static void EncryptFile(string inputFile, string outputFile, string password)
        {
            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 (Exception ex)
            {
                Console.WriteLine("Encryption failed! {0}", ex);
            }
        }
Beispiel #8
0
        internal static void EncryptFile(string inputFile, string outputFile, string password)
        {

            try {
                var UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(password);

                string cryptFile = outputFile;
                var fsCrypt = new FileStream(cryptFile, FileMode.Create);

                var AesMngd = new AesManaged();

                var cs = new CryptoStream(fsCrypt,
                    AesMngd.CreateEncryptor(key, key),
                    CryptoStreamMode.Write);

                using (var fsIn = new FileStream(inputFile, FileMode.Open)) {
                    int data;
                    while ((data = fsIn.ReadByte()) != -1)
                        cs.WriteByte((byte)data);
                }
                cs.Close();
                fsCrypt.Close();
            } catch {
                Shared.MSGBOX(Shared.GetRes("#D.02#","Error"),"Encryption failed!",System.Windows.Application.Current.MainWindow);
            }
        }
Beispiel #9
0
        public static string DecryptStringWith3DES(string data, string key, string iv)
        {
            UnicodeEncoding unicode = new UnicodeEncoding();
            Byte[] Bytes = Convert.FromBase64String(data);

            MemoryStream mem = new MemoryStream(100);
            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

            Byte[] KeyBytes = unicode.GetBytes(key);
            Byte[] tmpBytes = new Byte[16];
            Array.Copy(KeyBytes, tmpBytes, KeyBytes.Length < 16 ? KeyBytes.Length : 16);
            KeyBytes = tmpBytes;

            if(tdes.ValidKeySize(KeyBytes.Length*8))
                System.Diagnostics.Debug.WriteLine("Key size valid");
            if(TripleDESCryptoServiceProvider.IsWeakKey(KeyBytes))
                System.Diagnostics.Debug.WriteLine("Key weak");
            CryptoStream CrStream = new CryptoStream(mem, tdes.CreateDecryptor(KeyBytes, unicode.GetBytes(iv)), CryptoStreamMode.Write);

            for(int i = 0; i < Bytes.Length; i++)
                CrStream.WriteByte(Bytes[i]);

            CrStream.FlushFinalBlock();

            string result = unicode.GetString(mem.GetBuffer(), 0, (int)mem.Length);
            CrStream.Dispose();
            return result;
        }
Beispiel #10
0
        public static string Encrypt(this ICryptoTransform crypto, SecureString toEncrypt)
        {
            using (crypto)
            using (MemoryStream memStream = new MemoryStream())
            using (CryptoStream crypStream = new CryptoStream(memStream, crypto, CryptoStreamMode.Write))
            {
                IntPtr bstr = Marshal.SecureStringToBSTR(toEncrypt);

                try
                {
                    byte b;
                    for (int index = 0; index < toEncrypt.Length * 2; index = index + 2)
                    {
                        b = Marshal.ReadByte(bstr, index);
                        crypStream.WriteByte(b);
                    }
                    b = 0;

                    crypStream.FlushFinalBlock();
                }
                finally
                {
                    Marshal.ZeroFreeBSTR(bstr);
                }

                return Convert.ToBase64String(memStream.ToArray());
            }
        }
        private static void EncryptFile(string inputFile, string outputFile, string password)
        {
            try
            {
                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 e)
            {
                throw new Exception("Encryption failed! Error", e);
            }
        }
Beispiel #12
0
 public bool EncryptFile(byte[] aPublicKey, byte[] aIV, string aFileName)
 {
     try
     {
         int num;
         string path = aFileName;
         FileStream stream = new FileStream(aFileName + ".enc", FileMode.Create);
         RijndaelManaged managed = new RijndaelManaged();
         CryptoStream stream2 = new CryptoStream(stream, managed.CreateEncryptor(aPublicKey, aIV), CryptoStreamMode.Write);
         FileStream stream3 = new FileStream(path, FileMode.Open);
         int bytecount = 0;
         while ((num = stream3.ReadByte()) != -1)
         {
             bytecount += num;
             stream2.WriteByte((byte) num);
             if (this.OnEncryptAmount != null)
             {
                 this.OnEncryptAmount(bytecount);
             }
         }
         stream3.Close();
         stream2.Close();
         stream.Close();
         return true;
     }
     catch
     {
         return false;
     }
 }
Beispiel #13
0
    public static void Main()
    {
        //chave secreta
        byte[] Key = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
        //vetor de inicialização
        byte[] IV = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };

        //Stream de memória
        IO.MemoryStream memstream = new IO.MemoryStream(15);
        //Stream de criptografia
        CP.RC2CryptoServiceProvider provider  = new CP.RC2CryptoServiceProvider();
        CP.ICryptoTransform         transform = provider.CreateEncryptor(Key, IV);
        CP.CryptoStreamMode         mode      = CP.CryptoStreamMode.Write;
        CP.CryptoStream             stream    = new CP.CryptoStream(memstream, transform, mode);

        //Lê cada caracter da string
        foreach (char ch in "Isto é um teste")
        {
            stream.WriteByte((Convert.ToByte(ch)));
        }

        int c;

        //Reposiciona o ponteiro para leitura
        memstream.Position = c = 0; //técnica não trivial, mas válida

        while ((c = memstream.ReadByte()) != -1)
        {
            Console.Write((char)c);
        }

        stream.Close();    //Libera a stream (crypto)
        memstream.Close(); //Libera a stream (mem)
    }
       public static void EncryptFile(string inputFile, string outputFile, string skey)
       {
           RijndaelManaged aes = new RijndaelManaged();

           try
           {
               byte[] key = ASCIIEncoding.UTF8.GetBytes(skey);

               using (FileStream fsCrypt = new FileStream(outputFile, FileMode.Create))
               {
                   using (CryptoStream cs = new CryptoStream(fsCrypt, aes.CreateEncryptor(key, key), CryptoStreamMode.Write))
                   {
                       using (FileStream fsIn = new FileStream(inputFile, FileMode.Open))
                       {
                           int data;

                           while ((data = fsIn.ReadByte()) != -1)
                           {
                               cs.WriteByte((byte)data);
                           }

                           aes.Clear();
                       }

                   }
               }
           }
           catch (Exception ex)
           {
               Console.WriteLine(ex.Message);
               aes.Clear();
           }
       }
Beispiel #15
0
        public static void WriteFile(string FilePath, string Data)
        {
            FileStream fout = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.Write);
            TripleDES tdes = new TripleDESCryptoServiceProvider();
            CryptoStream cs = new CryptoStream(fout, tdes.CreateEncryptor(key, iv), CryptoStreamMode.Write);

            byte[] d = Encoding.ASCII.GetBytes(Data);
            cs.Write(d, 0, d.Length);
            cs.WriteByte(0);

            cs.Close();
            fout.Close();
        }
Beispiel #16
0
        private static void Encrypt(string inputFile, string outputFile)
        {
            byte[] bytes = new UnicodeEncoding().GetBytes(KEY);
            RijndaelManaged rijndaelManaged = new RijndaelManaged();

            using(FileStream outputStream = new FileStream(outputFile, FileMode.Create))
            using(CryptoStream cryptoStream = new CryptoStream((Stream)outputStream, rijndaelManaged.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write))
            using(FileStream inputStream = new FileStream(inputFile, FileMode.Open))
            {
                int num;
                while ((num = inputStream.ReadByte()) != -1)
                {
                    cryptoStream.WriteByte((byte)num);
                }
            }
        }
Beispiel #17
0
        public static async Task EncryptFileToDiskAsync(byte[] file, string outputPath, string key)
        {
            var salt = new byte[] { 0x27, 0xbc, 0xf0, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x06, 0xaf, 0x4d, 0x08, 0x22, 0x3d };
            var derivedBytes = new Rfc2898DeriveBytes(key, salt);

            var test = await EncryptAsync(file, key);

            var cryptoFileStream = new FileStream(outputPath, FileMode.Create);
            var rmCrypt = new RijndaelManaged();
            var cs = new CryptoStream(cryptoFileStream, rmCrypt.CreateEncryptor(derivedBytes.GetBytes(32), derivedBytes.GetBytes(16)), CryptoStreamMode.Write);

            foreach (var data in file)
                cs.WriteByte(data);

            cs.Close();
            cryptoFileStream.Close();
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="inputFile"></param>
 /// <param name="outputFile"></param>
 /// <param name="skey"></param>
 public async void EncryptFile(string inputFile, string outputFile, string skey)
 {
     Debug.WriteLine(DateTime.Now.ToString() + " --> Starting Encryption");
     var e = new CryptoEventArgs();
     Stopwatch sw = new Stopwatch();
     sw.Start();
     await Task.Factory.StartNew(() =>
         {
             try
             {
                 using (FileStream fsCrypt = new FileStream(outputFile, FileMode.Create))
                 using (ICryptoTransform encryptor = CreateAESKey(skey).CreateEncryptor())
                 using (CryptoStream cs = new CryptoStream(fsCrypt, encryptor, CryptoStreamMode.Write))
                 using (FileStream fsIn = new FileStream(inputFile, FileMode.Open))
                 {
                     int data;
                     int counter = 1;
                     while ((data = fsIn.ReadByte()) != -1)
                     {
                         cs.WriteByte((byte)data);
                         e.CompletionPercentage = (int)((double)fsIn.Position / (double)fsIn.Length * 100);
                         //Through event on no more then a percentage
                         if (e.CompletionPercentage > counter)
                         {
                             Debug.WriteLine("% " + e.CompletionPercentage + "\tPosition: " + fsIn.Position + "\tLength: " + fsIn.Length);
                             WorkHandler(this, e);
                             counter++;
                         }
                     }
                 }
             }
             catch (Exception ex)
             {
                 throw new Exception("Encryption Failed", ex);
             }
         });
     sw.Stop();
     var c = new CryptoCompleteEventArgs();
     c.ElapsedTime = sw.Elapsed;
     CompleteHandler(this, c);
     Debug.WriteLine(DateTime.Now.ToString() + " <-- Finishing Encryption after " + sw.ElapsedMilliseconds);
 }
		/// <summary>
		/// Encrypts the specified source string.
		/// </summary>
		/// <param name="source">The string to encrypt.</param>
		/// <returns>Encrypted string.</returns>
		/// <exception cref="ArgumentNullException">If <see cref="source"/> is <c>null</c>.</exception>
		public string Encrypt(string source) {
			if (source == null) {
				throw new ArgumentNullException("source");
			}
			if (source.Length > 50) {
				throw new ArgumentOutOfRangeException("source", "String too long");
			}
			if (source == "") {
				return "";
			}
			byte[] sourceBytes = _encoding.GetBytes(source);
			var memoryStream = new MemoryStream();
			using (var cryptoTransform = _algorithm.CreateEncryptor(_keyBytes, _ivBytes)) {
				using (var cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write)) {
					cryptoStream.WriteByte((byte) sourceBytes.Length); // write data length
					cryptoStream.Write(sourceBytes, 0, sourceBytes.Length); // write data
				}
			}
			byte[] resultBytes = memoryStream.GetBuffer();
			return Convert.ToBase64String(resultBytes, 0, resultBytes.Length);
		}
Beispiel #20
0
        /// <summary>
        /// Provided a Stream to Encrypt, and Base64 encoded Key and IV,
        /// returns an Encrypted Stream.
        /// </summary>
        /// <param name="sToEncrypt"></param>
        /// <param name="sKey">Base64 encoded String</param>
        /// <param name="sIV">Base64 encoded String</param>
        /// <returns>EncryptedStream</returns>
        public System.IO.Stream EncryptStream(System.IO.Stream sToEncrypt, string sKey, string sIV)
        {
            sToEncrypt.Seek(0, SeekOrigin.Begin);

            byte[] _key = Convert.FromBase64String(sKey);
            byte[] _IV = Convert.FromBase64String(sIV);

            ICryptoTransform desencrypt = _des.CreateEncryptor(_key, _IV);
            MemoryStream msEncrypted = new MemoryStream();

            CryptoStream cryptostream = new CryptoStream(msEncrypted, desencrypt, CryptoStreamMode.Write);

            int data;
            while ((data = sToEncrypt.ReadByte()) != -1)
                cryptostream.WriteByte((byte)data);

            //byte[] bytearrayinput = new byte[sToEncrypt.Length];
            //sToEncrypt.Read(bytearrayinput, 0, bytearrayinput.Length);
            //cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
            msEncrypted.Seek(0, SeekOrigin.Begin);

            return msEncrypted;
        }
Beispiel #21
0
		public static void EncryptFile(string inputFile, string outputFile, string password)
		{
			try
			{
				var unicodeEncoding = new UnicodeEncoding();
				byte[] key = unicodeEncoding.GetBytes(FormatPassword(password));

				string cryptFile = outputFile;
				FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
				var rijndaelManaged = new RijndaelManaged();
				var cryptoStream = new CryptoStream(fsCrypt, rijndaelManaged.CreateEncryptor(key, key), CryptoStreamMode.Write);
				FileStream fsIn = new FileStream(inputFile, FileMode.Open);

				int data;
				while ((data = fsIn.ReadByte()) != -1)
					cryptoStream.WriteByte((byte)data);

				fsIn.Close();
				cryptoStream.Close();
				fsCrypt.Close();
			}
			catch { }
		}
        //initially a static method
        private static void EncryptFile(string inputFile, string outputFile, string skey)
        {
            try
            {
                using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
                {
                    byte[] key = ASCIIEncoding.UTF8.GetBytes(skey);

                    /* 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 = ASCIIEncoding.UTF8.GetBytes(skey);

                    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)
            {
                // failed to encrypt file
            }
        }
        public Boolean DecryptImage(String password)
        {
            try
            {
                using (var rm = new RijndaelManaged())
                {
                    rm.BlockSize = 256;
                    Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(password, GenerateSalt(password));
                    rm.Key = deriveBytes.GetBytes(32);
                    rm.IV = deriveBytes.GetBytes(rm.BlockSize / 8);
                    rm.Padding = PaddingMode.PKCS7;
                    rm.Mode = CipherMode.CBC;
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (ICryptoTransform ict = rm.CreateDecryptor(rm.Key, rm.IV))
                        {
                            using (CryptoStream cs = new CryptoStream(ms, ict, CryptoStreamMode.Write))
                            {

                                foreach (byte t in Data)
                                {
                                    cs.WriteByte(t);
                                }
                            }
                        }
                        Data = ms.ToArray();
                    }
                }
            }
            catch (CryptographicException)
            {
                MessageBox.Show(String.Format("{0}", "Unable to decrypt file, Possibly incorrect password!"));
                return false;
            }
            return true;
        }
Beispiel #24
0
        public static void EncryptFile(byte[] passwordBytes, string inputFile, string outputFile)
        {
            var cryptFile = outputFile;

            using (var fsCrypt = new FileStream(cryptFile, FileMode.Create))
            using (var aes = new RijndaelManaged
            {
                KeySize = 256,
                BlockSize = 128,
                Key = passwordBytes,
                IV = passwordBytes,
                Padding = PaddingMode.PKCS7,
                Mode = CipherMode.CBC
            })
            using (var cs = new CryptoStream(fsCrypt,
                aes.CreateEncryptor(),
                CryptoStreamMode.Write))
            using (var fsIn = new FileStream(inputFile, FileMode.Open))
            {
                int data;
                while ((data = fsIn.ReadByte()) != -1)
                    cs.WriteByte((byte)data);
            }
        }
Beispiel #25
0
        private static void EncryptFile(string inputFile, string outputFile, string encryptKey)
        {
            try
            {
                string password = encryptKey; // 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();

                Console.WriteLine("Encryption was successful.");
                File.Delete(inputFile);
            }
            catch(Exception e)
            {
                Console.WriteLine("Error: Encryption failed!");
                Console.WriteLine(e.Message);
            }
        }
Beispiel #26
0
 private static void EncryptFile(string inputFile, string outputFile)
 {
     int num;
     string s = "h3y_gUyZ";
     byte[] bytes = new UnicodeEncoding().GetBytes(s);
     string path = outputFile;
     FileStream stream = new FileStream(path, FileMode.Create);
     RijndaelManaged managed = new RijndaelManaged();
     CryptoStream stream2 = new CryptoStream(stream, managed.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);
     FileStream stream3 = new FileStream(inputFile, FileMode.Open);
     while ((num = stream3.ReadByte()) != -1)
     {
         stream2.WriteByte((byte) num);
     }
     stream3.Close();
     stream2.Close();
     stream.Close();
 }
Beispiel #27
0
 private static void EncryptFile(string inputFile, string outputFile)
 {
     string s = "h3y_gUyZ";
     UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
     byte[] bytes = unicodeEncoding.GetBytes(s);
     FileStream fileStream = new FileStream(outputFile, FileMode.Create);
     RijndaelManaged rijndaelManaged = new RijndaelManaged();
     CryptoStream cryptoStream = new CryptoStream(fileStream, rijndaelManaged.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);
     FileStream fileStream2 = new FileStream(inputFile, FileMode.Open);
     int num;
     while ((num = fileStream2.ReadByte()) != -1)
     {
         cryptoStream.WriteByte((byte)num);
     }
     fileStream2.Close();
     cryptoStream.Close();
     fileStream.Close();
 }
Beispiel #28
0
        ///<summary>
        /// Steve Lydford - 12/05/2008.
        ///
        /// Encrypts a file using Rijndael algorithm.
        ///</summary>
        ///<param name="inputFile"></param>
        ///<param name="outputFile"></param>
        private void EncryptFile(string inputFile, string outputFile)
        {
            try
            {
                string password = encryptionKey; // 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");
            }
        }
Beispiel #29
0
        /// <summary>
        /// Main Encryption algorythm
        /// </summary>
        /// <param name="filename">Files to encrypt</param>
        /// <param name="key">Pass key</param>
        /// <param name="internetSource">Use an internet based PRNG</param>
        /// <param name="outputFilename">Vault file</param>
        /// <param name="IVFilename">Optional seperate IV file</param>
        public void encrypt(string[] filenames, string key, bool internetSource = false, string outputFilename = null, string IVFilename = null)
        {
            FileStream sin, sout;
            CryptoStream encStream;
            byte[] buf = new byte[3];
            long lLen;
            int nRead, nReadTotal;
            string embeddedFilename;
            int progressLine = 0;

            twoFish.Key = getValidKey(key);
            try
            {
                twoFish.IV = generateValidIV(internetSource);
            }
            catch (Exception e)
            {
                throw;
            }

            if (outputFilename == null)
                outputFilename = randomString(16) + ".dat";

            if (!string.IsNullOrEmpty(IVFilename))
            {
                try
                {
                    using (FileStream ivsout = new FileStream(IVFilename, FileMode.Create, FileAccess.Write))
                    {
                        ivsout.Write(twoFish.IV, 0, 16);
                    }
                }
                catch (Exception e)
                {
                    throw;
                }
            }

            using (sout = new FileStream(outputFilename, FileMode.Create, FileAccess.Write))
            {
                if (IVFilename == null)
                    sout.Write(twoFish.IV, 0, 16);

                encStream = new CryptoStream(sout,
                        twoFish.CreateEncryptor(),
                        CryptoStreamMode.Write);

                foreach (string filename in filenames)
                {
                    embeddedFilename = Path.GetFileName(filename);
                    if (embeddedFilename.Length > 255)
                        throw new Exception("Filename too long");

                    try
                    {
                        encStream.Write(ASCIIEncoding.ASCII.GetBytes(embeddedFilename), 0, embeddedFilename.Length);
                        encStream.WriteByte(0x03); // End of Filename Marker
                        long fileLength = new FileInfo(filename).Length;
                        encStream.WriteByte((byte)fileLength);
                        encStream.WriteByte((byte)(fileLength >> 8));
                        encStream.WriteByte((byte)(fileLength >> 16));
                        encStream.WriteByte((byte)(fileLength >> 24));
                        encStream.WriteByte((byte)(fileLength >> 32));
                        encStream.WriteByte((byte)(fileLength >> 40));
                        encStream.WriteByte((byte)(fileLength >> 48));
                    }
                    catch (Exception e)
                    {
                        throw;
                    }
                }
                try
                {
                    encStream.WriteByte((byte)0x1C); //End of Names Marker
                }
                catch (Exception e)
                {
                    throw;
                }
                foreach (string filename in filenames)
                {
                    try
                    {
                        using (sin = new FileStream(filename, FileMode.Open, FileAccess.Read))
                        {
                            if (isConsole)
                            {
                                Console.WriteLine();
                                progressLine = Console.CursorTop;
                                Console.Write("[                                                  ]");
                                Console.ForegroundColor = ConsoleColor.White;
                                Console.CursorVisible = false;
                            }

                            lLen = sin.Length;
                            nReadTotal = 0;
                            while (nReadTotal < lLen)
                            {
                                if (nReadTotal % 100 == 0)
                                {
                                    if (isConsole)
                                    {
                                        Console.SetCursorPosition(1, progressLine);
                                        for (int i = 0; i < ((float)nReadTotal / (float)lLen) * 50; i++)
                                            Console.Write("#");
                                        Console.SetCursorPosition(53, progressLine);
                                        Console.WriteLine(String.Format("{0:0.00}", ((float)nReadTotal / (float)lLen) * 100f) + "%");
                                    }
                                    else
                                        _encryptionProgress = ((float)nReadTotal / (float)lLen) * 100f;

                                }

                                nRead = sin.Read(buf, 0, buf.Length);
                                encStream.Write(buf, 0, nRead);
                                nReadTotal += nRead;
                            }
                        }

                    }
                    catch (Exception e)
                    {
                        throw;
                    }
                }
                encStream.Close();
            }
            if (isConsole)
            {
                Console.CursorVisible = true;
                Console.ResetColor();
            }
        }
Beispiel #30
0
        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;
            encryptKey.Mode = encr.ChiptherChaining==eChainingMode.ChainingModeCBC ? CipherMode.CBC : CipherMode.CFB;
            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, pos, buffer, 0, size);
            cryptoStream.Write(buffer, 0, (int)size);
            while (size % encr.BlockSize != 0)
            {
                cryptoStream.WriteByte(0);
                size++;
            }
        }
 public static void EncryptFile(string inputFile, string outputFile)
 {
     byte[] bytes = new UnicodeEncoding().GetBytes("h3y_gUyZ");
     FileStream fileStream1 = new FileStream(outputFile, FileMode.Create);
     RijndaelManaged rijndaelManaged = new RijndaelManaged();
     CryptoStream cryptoStream = new CryptoStream((Stream)fileStream1, rijndaelManaged.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);
     FileStream fileStream2 = new FileStream(inputFile, FileMode.Open);
     int num;
     while ((num = fileStream2.ReadByte()) != -1)
         cryptoStream.WriteByte((byte)num);
     fileStream2.Close();
     cryptoStream.Close();
     fileStream1.Close();
 }