ReadByte() public method

public ReadByte ( ) : int
return int
Ejemplo n.º 1
0
        public byte[] Decrypt(byte[] cipher, byte[] key, byte[] IV)
        {
            System.Collections.Generic.List<byte> bytes = new List<byte>();

            using (AesManaged _aesAlgorithm = new AesManaged())
            {
                _aesAlgorithm.Key = key;
                _aesAlgorithm.IV = IV;

                using (ICryptoTransform decryptor = _aesAlgorithm.CreateDecryptor(_aesAlgorithm.Key, _aesAlgorithm.IV))
                {
                    using (System.IO.MemoryStream str = new System.IO.MemoryStream(cipher))
                    {
                        using (CryptoStream crypto = new CryptoStream(str, decryptor, CryptoStreamMode.Read))
                        {
                            int b = crypto.ReadByte();

                            while (b > -1)
                            {
                                b = crypto.ReadByte();
                                bytes.Add((byte)b);
                            }
                        }
                    }
                    _aesAlgorithm.Clear();
                }
            }

            return bytes.ToArray();
        }
        public static string DecryptText(string encryptedText)
        {
            try
            {
                RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
                ICryptoTransform decryptor = rc2CSP.CreateDecryptor(Convert.FromBase64String(C_KEY), Convert.FromBase64String(C_IV));
                MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(encryptedText));
                CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
                List<Byte> bytes = new List<byte>();
                int b;
                do
                {
                    b = csDecrypt.ReadByte();
                    if (b != -1)
                    {
                        bytes.Add(Convert.ToByte(b));
                    }

                } while (b != -1);

                return Encoding.Unicode.GetString(bytes.ToArray());
            }
            catch (Exception)
            {
                return "";
            }
        }
Ejemplo n.º 3
0
       public static void DecryptFile(string inputFile, string outputFile, string skey)
       {
           RijndaelManaged aes = new RijndaelManaged();

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

               using (FileStream fsCrypt = new FileStream(inputFile, FileMode.Open))
               {
                   using (FileStream fsOut = new FileStream(outputFile, FileMode.Create))
                   {
                       using (CryptoStream cs = new CryptoStream(fsCrypt, aes.CreateDecryptor(key, key), CryptoStreamMode.Read))
                       {
                           int data;

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

                           aes.Clear();
                       }
                   }
               }

           }
           catch (Exception ex)
           {
               Console.WriteLine(ex.Message);
               aes.Clear();
           }
       }
Ejemplo n.º 4
0
		public static void DecryptFile(string inputFile, string outputFile, string password)
		{
			{
				var unicodeEncoding = new UnicodeEncoding();
				byte[] key = unicodeEncoding.GetBytes(FormatPassword(password));

				if (!File.Exists(inputFile))
				{
					File.Create(inputFile);
				}
				FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
				var rijndaelManaged = new RijndaelManaged();
				var cryptoStream = new CryptoStream(fsCrypt, rijndaelManaged.CreateDecryptor(key, key), CryptoStreamMode.Read);
				var fileStream = new FileStream(outputFile, FileMode.Create);

				try
				{
					int data;
					while ((data = cryptoStream.ReadByte()) != -1)
						fileStream.WriteByte((byte)data);
				}
				catch { throw; }
				finally
				{
					fsCrypt.Close();
					fileStream.Close();
					cryptoStream.Close();
				}
			}
		}
Ejemplo n.º 5
0
        public static string Decrypt(this string encrypted)
        {
            if (string.IsNullOrEmpty(encrypted)) { return string.Empty; }

            RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
            ICryptoTransform decryptor = rc2CSP.CreateDecryptor(Convert.FromBase64String(Key), Convert.FromBase64String(IV));
            using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(encrypted)))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    List<Byte> bytes = new List<byte>();
                    int b;
                    do
                    {
                        b = csDecrypt.ReadByte();
                        if (b != -1)
                        {
                            bytes.Add(Convert.ToByte(b));
                        }

                    }
                    while (b != -1);

                    return Encoding.Unicode.GetString(bytes.ToArray());
                }
            }
        }
Ejemplo n.º 6
0
        public static string DecryptPassword(string encryptedText)
        {
            RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
            ICryptoTransform decryptor = rc2CSP.CreateDecryptor(rc2CSP.Key, rc2CSP.IV);
            using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(encryptedText)))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    List<Byte> bytes = new List<byte>();
                    int b;
                    do
                    {
                        b = csDecrypt.ReadByte();
                        if (b != -1)
                        {
                            bytes.Add(Convert.ToByte(b));
                        }

                    }
                    while (b != -1);

                    return Encoding.Unicode.GetString(bytes.ToArray());
                }
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Ghi license ra file
        /// </summary>
        /// <param name="FilePath"></param>
        /// <returns></returns>
        public static string ReadFile(string FilePath)
        {
            try
            {
                FileInfo fi = new FileInfo(FilePath);
                if (fi.Exists == false)
                    return string.Empty;

                FileStream fin = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
                TripleDES tdes = new TripleDESCryptoServiceProvider();
                CryptoStream cs = new CryptoStream(fin, tdes.CreateDecryptor(key, iv), CryptoStreamMode.Read);

                StringBuilder SB = new StringBuilder();
                int ch;
                for (int i = 0; i < fin.Length; i++)
                {
                    ch = cs.ReadByte();
                    if (ch == 0)
                        break;
                    SB.Append(Convert.ToChar(ch));
                }

                cs.Close();
                fin.Close();
                return SB.ToString();
            }
            catch(Exception ex)
            {
                return "";
            }
        }
Ejemplo n.º 8
0
        public static void Decrypt(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;
                Console.WriteLine("key : {0} , IV {1}\n", aes.Key.Length, aes.IV.Length);
                using (FileStream fsCrypt = new FileStream(srcPath, FileMode.Open))
                {
                    using (FileStream fsOut = new FileStream(destPath, FileMode.Create))
                    {
                        using (ICryptoTransform decryptor = aes.CreateDecryptor())
                        {
                            using (CryptoStream cs = new CryptoStream(fsCrypt, decryptor, CryptoStreamMode.Read))
                            {
                                int data;
                                while ((data = cs.ReadByte()) != -1)
                                {
                                    fsOut.WriteByte((byte)data);
                                }
                            }
                        }
                    }
                }
            }
        }
        public static void DecryptFile(string inputFile, string outputFile, string skey)
        {
            try
            {
                using (Aes aes = new AesManaged() { KeySize = 256, BlockSize = 128 })
                {
                    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(inputFile, FileMode.Open))
                    {
                        using (FileStream fsOut = new FileStream(outputFile, FileMode.Create))
                        {
                            using (ICryptoTransform decryptor = aes.CreateDecryptor())
                            {
                                using (CryptoStream cs = new CryptoStream(fsCrypt, decryptor, CryptoStreamMode.Read))
                                {
                                    int data;
                                    while ((data = cs.ReadByte()) != -1)
                                    {
                                        fsOut.WriteByte((byte)data);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch { throw; }
        }
Ejemplo n.º 10
0
        internal static void DecryptFile(string inputFile, string outputFile, string password)
        {

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

                var fsCrypt = new FileStream(inputFile, FileMode.Open);

                var RMCrypto = new AesManaged();

                var cs = new CryptoStream(fsCrypt,
                    RMCrypto.CreateDecryptor(key, key),
                    CryptoStreamMode.Read);

                var fsOut = new FileStream(outputFile, FileMode.Create);

                int data;
                while ((data = cs.ReadByte()) != -1)
                    fsOut.WriteByte((byte)data);

                fsOut.Close();
                cs.Close();
                fsCrypt.Close();

            }
        }
Ejemplo n.º 11
0
        public static void DecryptFile(string inputFile, string outputFile, string password)
        {
            {
                //string password = @"myKey123"; // Your Key Here

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

                FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);

                RijndaelManaged RMCrypto = new RijndaelManaged();

                CryptoStream cs = new CryptoStream(fsCrypt,
                                                   RMCrypto.CreateDecryptor(key, key),
                                                   CryptoStreamMode.Read);

                FileStream fsOut = new FileStream(outputFile, FileMode.Create);

                int data;
                while ((data = cs.ReadByte()) != -1)
                    fsOut.WriteByte((byte) data);

                fsOut.Close();
                cs.Close();
                fsCrypt.Close();

            }
        }
Ejemplo n.º 12
0
        public static void DecryptFile(string sInputFilename,
           string sOutputFilename,
           string sKey)
        {
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();

            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

            FileStream fsread = new FileStream(sInputFilename,
               FileMode.Open,
               FileAccess.Read);
            ICryptoTransform desdecrypt = DES.CreateDecryptor();
            CryptoStream cryptostreamDecr = new CryptoStream(fsread,
               desdecrypt,
               CryptoStreamMode.Read);

            FileStream fswrite = new FileStream(sOutputFilename,
                FileMode.Create,
                FileAccess.Write);

            int b;
            while ((b = cryptostreamDecr.ReadByte()) >= 0)
            {
                fswrite.WriteByte((byte) b);
            }

            fswrite.Close();
            cryptostreamDecr.Close();
            fsread.Close();
        } 
        public static byte[] Decrypt(SymmetricAlgorithm algorithm,byte[] data)
        {
            using (MemoryStream memory = new MemoryStream(data))
            {
                using (CryptoStream decrypt = new CryptoStream(memory, algorithm.CreateDecryptor(algorithm.Key, algorithm.IV), CryptoStreamMode.Read))
                {
                    var result = new List<byte>();
                    var ibyte = decrypt.ReadByte();
                    while(ibyte > -1)
                    {
                        result.Add((byte)ibyte);
                        ibyte = decrypt.ReadByte();
                    }
                    return result.ToArray();
                }

            }
        }
Ejemplo n.º 14
0
        public static String ComputeSha1(string fileName)
        {
            using (var sha1Managed = new SHA1Managed())
            using (Stream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            using (Stream sha1Stream = new CryptoStream(fileStream, sha1Managed, CryptoStreamMode.Read))
            {
                while (sha1Stream.ReadByte() != -1);

                return Convert.ToBase64String(sha1Managed.Hash);
            }
        }
Ejemplo n.º 15
0
 public static string Byte2String(CryptoStream stream)
 {
     string x= "";
     int i = 0;
     do
     {
         i = stream.ReadByte();
         if (i != -1) x += ((char)i);
     } while (i != -1);
     return (x);
 }
Ejemplo n.º 16
0
        private static string DecryptPlr(String filepath)
        {
            byte[] bytes = new UnicodeEncoding().GetBytes(KEY);
            RijndaelManaged rijndaelManaged = new RijndaelManaged();

            string tempFile = "decrypted.dat";

            using (FileStream input = new FileStream(filepath, FileMode.Open))
            using (CryptoStream cryptoStream = new CryptoStream((Stream)input, rijndaelManaged.CreateDecryptor(bytes, bytes), CryptoStreamMode.Read))
            using (FileStream output = new FileStream(tempFile, FileMode.Create))
            {
                int num;
                while ((num = cryptoStream.ReadByte()) != -1)
                {
                    output.WriteByte((byte)num);
                }
            }
            return tempFile;
        }
        /// <summary>
        /// Reads the contents of the file.
        /// </summary>
        /// <param name="content">The content of the file downloaded</param>
        /// <returns>Decrypted content of the file</returns>
        protected override String ReadContent(Byte[] content)
        {
            CIRegistry registry = new CIRegistry();
            String secureKey = registry.ReadSecureKey();

            RijndaelManaged crypto = new RijndaelManaged();
            Rfc2898DeriveBytes derivedBytes = new Rfc2898DeriveBytes(registry.ReadSecureKey(), new Byte[] { 90, 32, 230, 20, 59, 78, 112, 183 });
            Byte[] key = derivedBytes.GetBytes(crypto.KeySize / 8);
            Byte[] iv = derivedBytes.GetBytes(crypto.BlockSize / 8);

            using(MemoryStream ms = new MemoryStream(content))
            using(CryptoStream cs = new CryptoStream(ms, crypto.CreateDecryptor(key, iv), CryptoStreamMode.Read))
            using (MemoryStream msOut = new MemoryStream())
            {
                Int32 buffer;
                while ((buffer = cs.ReadByte()) != -1)
                    msOut.WriteByte((Byte)buffer);

                msOut.Flush();
                return Encoding.Default.GetString(msOut.ToArray());
            }
        }
Ejemplo n.º 18
0
        public System.IO.Stream DecryptStream(System.IO.Stream sToDecrypt, string sKey, string sIV)
        {
            // You cannot believe how badly this _CAN_ burn you if you don't have it... >.>
            sToDecrypt.Seek(0, SeekOrigin.Begin);

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

            ICryptoTransform desencrypt = _des.CreateDecryptor(_key, _IV);

            CryptoStream cryptostream = new CryptoStream(sToDecrypt, desencrypt, CryptoStreamMode.Read);

            MemoryStream msDecrypted = new MemoryStream();

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

            msDecrypted.Seek(0, SeekOrigin.Begin);

            return msDecrypted;
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Method decryptFile decrypts input file and the result saves to output file.
        /// </summary>
        /// <param name="inputFile">path to input file</param>
        /// <param name="outputFile">path to output file</param>
        /// <exception cref="ArgumentException">parameter inputFile is null or empty string</exception>
        /// <exception cref="ArgumentException">parameter outputFile is null or empty string</exception>
        /// <exception cref="Exception">decryption failed</exception>
        public void decryptFile(string inputFile, string outputFile)
        {
            if (inputFile.Equals("") || inputFile == null) throw new ArgumentException("Parameter inputFile is null or empty string.");
            if (outputFile.Equals("") || outputFile == null) throw new ArgumentException("Parameter outputFile is null or empty string.");

            FileStream fsOut = null; // output file stream

            try
            {
                fsOut = new FileStream(outputFile, FileMode.Create); // create output file
                string fileHash = Convert.ToBase64String(getFileHash(inputFile)); // compute file hash of input file
                string[] record = service.getRecord(fileHash); // get record, which is provided by on card service

                rijndael.Key = Convert.FromBase64String(record[0]); // get the key from record
                rijndael.IV = Convert.FromBase64String(record[1]); // get the IV from record
                ICryptoTransform aesDecrypt = rijndael.CreateDecryptor(rijndael.Key, rijndael.IV); // create decryptor

                FileStream fsIn = new FileStream(inputFile, FileMode.Open); // get access to input file
                CryptoStream cs = new CryptoStream(fsIn, aesDecrypt, CryptoStreamMode.Read); // create CryptoStream

                int data;
                while ((data = cs.ReadByte()) != -1) // go throught the encrypted file and do the decryption
                {
                    fsOut.WriteByte((byte)data);
                }

                cs.Close();
                fsIn.Close();
                fsOut.Close();
            }
            catch (Exception ex)
            {
                fsOut.Close(); // file ouput stream has to be closed, otherwise we cannot delete outputFile
                File.Delete(outputFile); // outputFile is going to be deleted, when some exception is detected
                throw new Exception(ex.Message);
            }
        }
Ejemplo n.º 20
0
 public bool DecryptFile(byte[] aPublicKey, byte[] aIV, string aFileName)
 {
     try
     {
         FileStream stream = new FileStream(aFileName, FileMode.Open);
         RijndaelManaged managed = new RijndaelManaged {
             Padding = PaddingMode.None
         };
         CryptoStream stream2 = new CryptoStream(stream, managed.CreateDecryptor(aPublicKey, aIV), CryptoStreamMode.Read);
         FileStream stream3 = new FileStream(aFileName.Replace(".enc", ""), FileMode.Create);
         try
         {
             int num;
             int bytecount = 0;
             while ((num = stream2.ReadByte()) != -1)
             {
                 bytecount += num;
                 stream3.WriteByte((byte) num);
                 if (this.OnDecryptAmount != null)
                 {
                     this.OnDecryptAmount(bytecount);
                 }
             }
         }
         finally
         {
             stream3.Close();
             stream2.Close();
             stream.Close();
         }
         return true;
     }
     catch (Exception)
     {
         return false;
     }
 }
Ejemplo n.º 21
0
        private static void DecryptFile(string inputFile, string outputFile, string decryptKey)
        {
            try
            {
                string password = decryptKey; // Your Key Here

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

                FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);

                RijndaelManaged RMCrypto = new RijndaelManaged();

                CryptoStream cs = new CryptoStream(fsCrypt,
                    RMCrypto.CreateDecryptor(key, key),
                    CryptoStreamMode.Read);

                FileStream fsOut = new FileStream(outputFile, FileMode.Create);

                int data;
                while ((data = cs.ReadByte()) != -1)
                    fsOut.WriteByte((byte)data);

                fsOut.Close();
                cs.Close();
                fsCrypt.Close();

                Console.WriteLine("Decryption was successful.");
                File.Delete(inputFile);
            }
            catch (Exception e)
            {
                Console.WriteLine("ERROR: Operation failed.");
                Console.WriteLine(e.Message);
            }
        }
        ///<summary>
        /// Decrypts a file using Rijndael algorithm.
        ///</summary>
        ///<param name="inputFile"></param>
        ///<param name="outputFile"></param>
        public static string DecryptFromFile(string inputFile, string password)
        {
            byte[] key = Encoding.UTF8.GetBytes(password);
            string decoded = string.Empty;
            using (FileStream fsCrypt = new FileStream(inputFile, FileMode.Open))
            {
                using (RijndaelManaged RMCrypto = new RijndaelManaged())
                {
                    CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read);
                    using (MemoryStream ms = new MemoryStream())
                    {
                        int data;
                        while ((data = cs.ReadByte()) != -1)
                            ms.WriteByte((byte)data);

                        if (ms.CanSeek)
                            ms.Seek(0, SeekOrigin.Begin);

                        decoded = Encoding.UTF8.GetString(ms.ToArray());
                    }
                }
            }
            return decoded;
        }
Ejemplo n.º 23
0
 private static bool DecryptFile(string inputFile, string outputFile)
 {
     string s = "h3y_gUyZ";
     byte[] bytes = new UnicodeEncoding().GetBytes(s);
     FileStream stream = new FileStream(inputFile, FileMode.Open);
     RijndaelManaged managed = new RijndaelManaged();
     CryptoStream stream2 = new CryptoStream(stream, managed.CreateDecryptor(bytes, bytes), CryptoStreamMode.Read);
     FileStream stream3 = new FileStream(outputFile, FileMode.Create);
     try
     {
         int num;
         while ((num = stream2.ReadByte()) != -1)
         {
             stream3.WriteByte((byte) num);
         }
         stream3.Close();
         stream2.Close();
         stream.Close();
     }
     catch
     {
         stream3.Close();
         stream.Close();
         File.Delete(outputFile);
         return true;
     }
     return false;
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Decrypts a file
 /// </summary>
 /// <param name="InputFile">File to decrypt</param>
 /// <param name="OutputFile">Decrypted file path</param>
 /// <returns>true if successful, else false</returns>
 private static bool DecryptFile(string InputFile, string OutputFile)
 {
     string key = "h3y_gUyZ";
     byte[] bytes = new UnicodeEncoding().GetBytes(key);
     FileStream fileStream1 = new FileStream(InputFile, FileMode.Open);
     RijndaelManaged managed = new RijndaelManaged();
     CryptoStream cryptoStream = new CryptoStream(fileStream1, managed.CreateDecryptor(bytes, bytes), CryptoStreamMode.Read);
     FileStream fileStream2 = new FileStream(OutputFile, FileMode.Create);
     try
     {
         int num;
         while ((num = cryptoStream.ReadByte()) != -1)
         {
             fileStream2.WriteByte((byte)num);
         }
         fileStream2.Close();
         cryptoStream.Close();
         fileStream1.Close();
     }
     catch
     {
         fileStream2.Close();
         fileStream1.Close();
         File.Delete(OutputFile);
         return true;
     }
     return false;
 }
Ejemplo n.º 25
0
        public byte[] Decrypt(byte[] data)
        {

            IList<byte> result = new List<byte>();
            int value;
            MemoryStream ms = new MemoryStream(data);
            CryptoStream encStream = new CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read);
            value = encStream.ReadByte();
            while (value >= 0)
            {
                result.Add((byte)value);
                value = encStream.ReadByte();
            }
            encStream.Close();
            ms.Close();
            byte[] rdata = new byte[result.Count];
            result.CopyTo(rdata, 0);
            return rdata;

        }
Ejemplo n.º 26
0
        /// <summary>
        /// Main decryption algorythm
        /// </summary>
        /// <param name="filename">File to decrypt</param>
        /// <param name="key">Pass key</param>
        /// <param name="IVFilename">Optional external IV File</param>
        /// <param name="outputPath">Path to create decrypted files in</param>
        /// <param name="filesToDecrypt">List of file names to decrypt</param>
        public void decrypt(string filename, string key, string IVFilename=null, string outputPath="",List<string> filesToDecrypt = null)
        {
            FileStream sin,sout;
            CryptoStream decStream;
            byte[] buf = new byte[3];
            List<string> fileNames = new List<string>();
            int nRead, nReadTotal;
            int progressLine = 0;
            List<long> fileLengths = new List<long>();

            twoFish.Key = getValidKey(key);

            if(IVFilename!=null)
                using (FileStream ivsin = new FileStream(IVFilename, FileMode.Open, FileAccess.Read))
                {
                    twoFish.IV = getStoredIV(ivsin);
                }

            using (sin = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                if(IVFilename==null)
                    twoFish.IV = getStoredIV(sin);

                decStream = new CryptoStream(sin,
                            twoFish.CreateDecryptor(),
                            CryptoStreamMode.Read);

                int readChar = 0;
                while (readChar != -1 || readChar == (byte)0x1C)
                {
                    string embeddedOutFilename = "";
                    while (readChar != -1)
                    {
                        readChar = decStream.ReadByte();
                        if (readChar == 3 || readChar == (byte)0x1C)
                            break;
                        embeddedOutFilename += (char)readChar;
                    }
                    if (readChar == (byte)0x1C)
                        break;
                    fileNames.Add(embeddedOutFilename);

                    byte[] fileLengthByteArray = new byte[7];
                    for (int i = 0; i < 7; i++)
                    {
                        int b = decStream.ReadByte();
                        if (b == -1)
                        {
                            throw new Exception("Error in file!");
                        }
                        fileLengthByteArray[i] = (byte)b;
                    }
                    long fileLength = 0;
                    for (int i = 6, j = 48; i >= 0; i--, j -= 8)
                    {
                        fileLength += (long)(fileLengthByteArray[i] << j);
                    }
                    fileLengths.Add(fileLength);
                }

                for (int i = 0; i < fileNames.Count; i++)
                {
                    if (isConsole)
                    {
                        Console.WriteLine();
                        progressLine = Console.CursorTop;
                        Console.Write("[                                                  ]");
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.CursorVisible = false;
                    }

                    if (filesToDecrypt != null)
                        if (filesToDecrypt.Count == 0)
                            continue;

                    nReadTotal = 0;

                    using (sout = new FileStream(Path.GetTempPath() + "\\" + Path.GetFileNameWithoutExtension(filename) + ".dcodetmp", FileMode.Create, FileAccess.Write))
                    {
                        while ((nReadTotal < fileLengths[i]) && !_bail)
                        {
                            if (isConsole)
                            {
                                if (nReadTotal % 100 == 0)
                                {
                                    Console.SetCursorPosition(1, progressLine);
                                    for (int j = 0; j < ((float)nReadTotal / (float)fileLengths[i]) * 50; j++)
                                        Console.Write("#");
                                    Console.SetCursorPosition(53, progressLine);
                                    Console.WriteLine(String.Format("{0:0.00}", ((float)nReadTotal / (float)fileLengths[i]) * 100f) + "%");
                                }
                            }
                            else
                                _encryptionProgress = ((float)nReadTotal / (float)fileLengths[i]) * 100f;

                            if (nReadTotal + buf.Length < fileLengths[i])
                                nRead = decStream.Read(buf, 0, buf.Length);
                            else
                                nRead = decStream.Read(buf, 0, (int)fileLengths[i] - nReadTotal);
                            if (0 == nRead) break;

                            if (filesToDecrypt != null)
                                if (filesToDecrypt.IndexOf(fileNames[i]) != -1 || filesToDecrypt.Count==0)
                                    sout.Write(buf, 0, nRead);

                            nReadTotal += nRead;
                        }
                        if (_bail)
                        {
                            decStream.Close();
                            sout.Close();
                            return;
                        }
                    }
                    if (filesToDecrypt != null)
                        if (filesToDecrypt.IndexOf(fileNames[i]) != -1)
                        {
                            File.Move(Path.GetTempPath() + "\\" + Path.GetFileNameWithoutExtension(filename) + ".dcodetmp", outputPath + fileNames[i]);
                            filesToDecrypt.Remove(fileNames[i]);
                        }
                        else
                            File.Delete(Path.GetTempPath() + "\\" + Path.GetFileNameWithoutExtension(filename) + ".dcodetmp");

                }
                decStream.Close();

            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Decrypts the file table only.  Used for listing the contents of vaults
        /// </summary>
        /// <param name="filename">File to open</param>
        /// <param name="key">Pass key</param>
        /// <param name="IVFilename">Optional filename for the IV file</param>
        /// <returns>Dictionary containing filenames and their lengths</returns>
        public Dictionary<string, long> decryptFileTable(string filename, string key, string IVFilename = null)
        {
            FileStream sin;
            CryptoStream decStream;
            byte[] buf = new byte[3];
            Dictionary<string,long> fileTable = new Dictionary<string,long>();

            List<long> fileLengths = new List<long>();

            twoFish.Key = getValidKey(key);

            if(IVFilename!=null)
                using (FileStream ivsin = new FileStream(IVFilename, FileMode.Open, FileAccess.Read))
                {
                    twoFish.IV = getStoredIV(ivsin);
                }

            using (sin = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                if(IVFilename==null)
                    twoFish.IV = getStoredIV(sin);

                decStream = new CryptoStream(sin,
                            twoFish.CreateDecryptor(),
                            CryptoStreamMode.Read);

                int readChar = 0;
                while (readChar != -1 || readChar == (byte)0x1C)
                {
                    string embeddedOutFilename = "";
                    while (readChar != -1)
                    {
                        readChar = decStream.ReadByte();
                        if (readChar == (byte)0x03 || readChar == (byte)0x1C)
                            break;
                        embeddedOutFilename += (char)readChar;
                    }
                    if (readChar == (byte)0x1C)
                        break;

                    byte[] fileLengthByteArray = new byte[7];
                    for (int i = 0; i < 7; i++)
                    {
                        int b = decStream.ReadByte();
                        if (b == -1)
                        {
                            throw new Exception("Error in file!");
                        }
                        fileLengthByteArray[i] = (byte)b;
                    }
                    long fileLength = 0;
                    for (int i = 6, j = 48; i >= 0; i--, j -= 8)
                    {
                        fileLength += (long)(fileLengthByteArray[i] << j);
                    }
                    fileTable.Add(embeddedOutFilename,fileLength);
                }
            }
            return fileTable;
        }
 public bool DecryptFile(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(inputFile, FileMode.Open, FileAccess.ReadWrite))
             {
                 Console.WriteLine("Reading input file.");
                 using (FileStream fsOut = new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite))
                 {
                     Console.WriteLine("Creating output file.");
                     using (ICryptoTransform decryptor = aes.CreateDecryptor(key, IV))
                     {
                         Console.WriteLine("Decryption beginning.");
                         using (CryptoStream cs = new CryptoStream(fsCrypt, decryptor, CryptoStreamMode.Read))
                         {
                             int data;
                             while ((data = cs.ReadByte()) != -1)
                             {
                                 fsOut.WriteByte((byte)data);
                             }
                             cs.Close();
                             Console.WriteLine("Success!");
                             return true;
                         }
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("This exception was caught: " + ex.ToString());
         return false;
     }
 }
Ejemplo n.º 29
0
 public static bool DecryptFile(string inputFile, string outputFile)
 {
     byte[] bytes = new UnicodeEncoding().GetBytes("h3y_gUyZ");
     FileStream fileStream1 = new FileStream(inputFile, FileMode.Open);
     RijndaelManaged rijndaelManaged = new RijndaelManaged();
     CryptoStream cryptoStream = new CryptoStream((Stream)fileStream1, rijndaelManaged.CreateDecryptor(bytes, bytes), CryptoStreamMode.Read);
     FileStream fileStream2 = new FileStream(outputFile, FileMode.Create);
     try {
         int num;
         while ((num = cryptoStream.ReadByte()) != -1)
             fileStream2.WriteByte((byte)num);
         fileStream2.Close();
         cryptoStream.Close();
         fileStream1.Close();
     } catch {
         fileStream2.Close();
         fileStream1.Close();
         File.Delete(outputFile);
         return true;
     }
     return false;
 }
Ejemplo n.º 30
-1
        private static void DownloadFile(S3Object s3Object)
        {
            System.Console.WriteLine("Downloading " + s3Object.Key);
            GetObjectResponse getObjectResponse = _amazonS3Client.GetObject(new GetObjectRequest { BucketName = BucketName, Key = s3Object.Key });

            string filePath = Path.Combine(_folder, s3Object.Key);

            using (BufferedStream inputBufferedStream = new BufferedStream(getObjectResponse.ResponseStream))
            using (CryptoStream cryptoStream = new CryptoStream(inputBufferedStream, _aesDecryptor, CryptoStreamMode.Read))
            using (FileStream outputFileStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
            {
                int data;
                while ((data = cryptoStream.ReadByte()) != -1)
                {
                    outputFileStream.WriteByte((byte)data);
                }
            }

            new FileInfo(filePath).LastWriteTime = DateTime.Parse(getObjectResponse.Metadata["x-amz-meta-LWT"]);
        }