Example #1
0
        public void SecureFile_File_Validate()
        {
            string         originalName = Path.GetTempFileName();
            string         encryptName  = Path.GetTempFileName();
            string         privateKey   = AsymmetricCrypto.CreatePrivateKey(CryptoAlgorithm.RSA, 1024);
            string         publicKey    = AsymmetricCrypto.GetPublicKey(CryptoAlgorithm.RSA, privateKey);
            EnhancedStream original     = null;
            EnhancedStream encrypted    = null;
            SecureFile     secure       = null;
            byte           b;

            try
            {
                original = new EnhancedFileStream(originalName, FileMode.Create, FileAccess.ReadWrite);

                for (int i = 0; i < 100; i++)
                {
                    original.WriteByte((byte)i);
                }

                original.Close();
                original = null;

                secure = new SecureFile(originalName, SecureFileMode.Encrypt, publicKey);
                secure.EncryptTo(encryptName, CryptoAlgorithm.AES, 256);
                secure.Close();
                secure = null;

                Assert.IsTrue(SecureFile.Validate(encryptName, privateKey));

                encrypted          = new EnhancedFileStream(encryptName, FileMode.Open, FileAccess.ReadWrite);
                encrypted.Position = encrypted.Length - 1;
                b = (byte)encrypted.ReadByte();
                encrypted.Position = encrypted.Length - 1;
                encrypted.WriteByte((byte)(~b));
                encrypted.Close();

                Assert.IsFalse(SecureFile.Validate(encryptName, privateKey));
            }
            finally
            {
                if (original != null)
                {
                    original.Close();
                }

                if (encrypted != null)
                {
                    encrypted.Close();
                }

                System.IO.File.Delete(originalName);
                System.IO.File.Delete(encryptName);
            }
        }
Example #2
0
        private void CompareFiles(string path1, string path2)
        {
            EnhancedFileStream es1 = null;
            EnhancedFileStream es2 = null;

            try
            {
                es1 = new EnhancedFileStream(path1, FileMode.Open, FileAccess.Read);
                es2 = new EnhancedFileStream(path2, FileMode.Open, FileAccess.Read);

                Assert.AreEqual(es1.Length, es2.Length);
                CollectionAssert.AreEqual(MD5Hasher.Compute(es1, es1.Length), MD5Hasher.Compute(es2, es2.Length));
            }
            finally
            {
                if (es1 != null)
                {
                    es1.Close();
                }

                if (es2 != null)
                {
                    es2.Close();
                }
            }
        }
Example #3
0
        private void WriteFile(string path, byte[] data)
        {
            var es = new EnhancedFileStream(path, FileMode.Create);

            es.WriteBytesNoLen(data);
            es.Close();
        }
Example #4
0
        /// <summary>
        /// Extracts files from a ZIP archive file.
        /// </summary>
        /// <param name="zipPath">Path to the input ZIP archive.</param>
        /// <param name="targetFolder">Path to the output folder.</param>
        /// <param name="createFolder">Pass <c>true</c> to place the output in a subfolder named for the ZIP archive.</param>
        public static void Unzip(string zipPath, string targetFolder, bool createFolder)
        {
            ZipFile archive = null;
            string  outPath;

            try
            {
                archive = new ZipFile(zipPath);
                outPath = targetFolder;

                if (createFolder)
                {
                    outPath = Path.Combine(outPath, Helper.GetFileNameWithoutExtension(zipPath));
                }

                foreach (ZipEntry entry in archive)
                {
                    Stream         inStream  = null;
                    EnhancedStream outStream = null;
                    string         outFile;

                    outFile = Path.Combine(outPath, entry.Name);
                    Helper.CreateFileTree(outFile);

                    try
                    {
                        inStream  = archive.GetInputStream(entry);
                        outStream = new EnhancedFileStream(outFile, FileMode.Create, FileAccess.ReadWrite);

                        outStream.CopyFrom(inStream, -1);
                    }
                    finally
                    {
                        if (inStream != null)
                        {
                            inStream.Close();
                        }

                        if (outStream != null)
                        {
                            outStream.Close();
                        }

                        File.SetCreationTime(outFile, entry.DateTime);
                        File.SetLastWriteTime(outFile, entry.DateTime);
                    }
                }
            }
            finally
            {
                if (archive != null)
                {
                    archive.Close();
                }
            }
        }
Example #5
0
 /// <summary>
 /// Closes the log file if it's open.
 /// </summary>
 public void Close()
 {
     using (TimedLock.Lock(this))
     {
         if (file != null)
         {
             file.Close();
             file = null;
         }
     }
 }
Example #6
0
        /// <summary>
        /// Closes the store, releasing any resources.
        /// </summary>
        public void Close()
        {
            if (fsIndex != null)
            {
                SaveIndex(false);

                fsIndex.Close();
                fsIndex = null;
            }

            messages = null;
        }
Example #7
0
        public void SecureFile_File_GetPublicKey()
        {
            string         originalName = Path.GetTempFileName();
            string         encryptName  = Path.GetTempFileName();
            string         privateKey   = AsymmetricCrypto.CreatePrivateKey(CryptoAlgorithm.RSA, 1024);
            string         publicKey    = AsymmetricCrypto.GetPublicKey(CryptoAlgorithm.RSA, privateKey);
            EnhancedStream original     = null;
            EnhancedStream encrypted    = null;
            SecureFile     secure       = null;

            try
            {
                original = new EnhancedFileStream(originalName, FileMode.Create, FileAccess.ReadWrite);

                for (int i = 0; i < 100; i++)
                {
                    original.WriteByte((byte)i);
                }

                original.Close();
                original = null;

                // Verify that the public key is saved if requested

                secure = new SecureFile(originalName, SecureFileMode.Encrypt, publicKey);
                Assert.IsTrue(secure.SavePublicKey);
                Assert.AreEqual(publicKey, secure.PublicKey);
                secure.EncryptTo(encryptName, CryptoAlgorithm.AES, 256);
                secure.Close();
                secure = null;

                Assert.AreEqual(publicKey, SecureFile.GetPublicKey(encryptName));

                // Verify that the public key is not saved, if SavePublicKey=false

                System.IO.File.Delete(encryptName);

                secure = new SecureFile(originalName, SecureFileMode.Encrypt, publicKey);
                secure.SavePublicKey = false;
                secure.EncryptTo(encryptName, CryptoAlgorithm.AES, 256);
                secure.Close();
                secure = null;

                Assert.IsNull(SecureFile.GetPublicKey(encryptName));
            }
            finally
            {
                if (original != null)
                {
                    original.Close();
                }

                if (encrypted != null)
                {
                    encrypted.Close();
                }

                System.IO.File.Delete(originalName);
                System.IO.File.Delete(encryptName);
            }
        }
Example #8
0
        public void SecureFile_File_Metadata()
        {
            string         originalName = Path.GetTempFileName();
            string         encryptName  = Path.GetTempFileName();
            string         decryptName  = Path.GetTempFileName();
            string         privateKey   = AsymmetricCrypto.CreatePrivateKey(CryptoAlgorithm.RSA, 1024);
            string         publicKey    = AsymmetricCrypto.GetPublicKey(CryptoAlgorithm.RSA, privateKey);
            EnhancedStream original     = null;
            EnhancedStream encrypted    = null;
            EnhancedStream decrypted    = null;
            SecureFile     secure       = null;
            DateTime       createTime   = Helper.UtcNowRounded - TimeSpan.FromMinutes(1);
            DateTime       writeTime    = Helper.UtcNowRounded;

            try
            {
                original = new EnhancedFileStream(originalName, FileMode.Create, FileAccess.ReadWrite);

                for (int i = 0; i < 100; i++)
                {
                    original.WriteByte((byte)i);
                }

                original.Close();
                original = null;

                Directory.SetCreationTimeUtc(originalName, createTime);
                Directory.SetLastWriteTimeUtc(originalName, writeTime);

                secure = new SecureFile(originalName, SecureFileMode.Encrypt, publicKey);
                secure.Properties["Foo"]   = "Bar";
                secure.Properties["Hello"] = "World";
                secure.EncryptTo(encryptName, CryptoAlgorithm.AES, 256);
                Assert.AreEqual(Path.GetFileName(originalName), secure.FileName);
                Assert.AreEqual(createTime, secure.CreateTimeUtc);
                Assert.AreEqual(writeTime, secure.WriteTimeUtc);
                secure.Close();
                secure = null;

                secure = new SecureFile(encryptName, SecureFileMode.Decrypt, privateKey);
                Assert.AreEqual("Bar", secure.Properties["Foo"]);
                Assert.AreEqual("World", secure.Properties["Hello"]);
                Assert.AreEqual(Path.GetFileName(originalName), secure.FileName);
                Assert.AreEqual(createTime, secure.CreateTimeUtc);
                Assert.AreEqual(writeTime, secure.WriteTimeUtc);
                secure.DecryptTo(decryptName);
                secure.Close();
                secure = null;

                Assert.AreEqual(createTime, Directory.GetCreationTimeUtc(decryptName));
                Assert.AreEqual(writeTime, Directory.GetLastWriteTimeUtc(decryptName));

                original  = new EnhancedFileStream(originalName, FileMode.Open, FileAccess.Read);
                encrypted = new EnhancedFileStream(encryptName, FileMode.Open, FileAccess.Read);
                decrypted = new EnhancedFileStream(decryptName, FileMode.Open, FileAccess.Read);

                original.Position  = 0;
                encrypted.Position = 0;
                Assert.AreNotEqual(original.ReadBytesToEnd(), encrypted.ReadBytesToEnd());

                original.Position  = 0;
                decrypted.Position = 0;
                CollectionAssert.AreEqual(original.ReadBytesToEnd(), decrypted.ReadBytesToEnd());
            }
            finally
            {
                if (original != null)
                {
                    original.Close();
                }

                if (encrypted != null)
                {
                    encrypted.Close();
                }

                if (decrypted != null)
                {
                    decrypted.Close();
                }

                System.IO.File.Delete(originalName);
                System.IO.File.Delete(encryptName);
                System.IO.File.Delete(decryptName);
            }
        }
Example #9
0
        public void SecureFile_File_BadHash()
        {
            string         originalName = Path.GetTempFileName();
            string         encryptName  = Path.GetTempFileName();
            string         decryptName  = Path.GetTempFileName();
            string         privateKey   = AsymmetricCrypto.CreatePrivateKey(CryptoAlgorithm.RSA, 1024);
            string         publicKey    = AsymmetricCrypto.GetPublicKey(CryptoAlgorithm.RSA, privateKey);
            EnhancedStream original     = null;
            EnhancedStream encrypted    = null;
            SecureFile     secure       = null;
            byte           b;

            try
            {
                original = new EnhancedFileStream(originalName, FileMode.Create, FileAccess.ReadWrite);

                for (int i = 0; i < 100; i++)
                {
                    original.WriteByte((byte)i);
                }

                original.Close();
                original = null;

                secure = new SecureFile(originalName, SecureFileMode.Encrypt, publicKey);
                secure.EncryptTo(encryptName, CryptoAlgorithm.AES, 256);
                secure.Close();
                secure = null;

                // Munge the last byte of the hash digest and then confirm
                // that the bad hash is detected.

                encrypted          = new EnhancedFileStream(encryptName, FileMode.Open, FileAccess.ReadWrite);
                encrypted.Position = encrypted.Length - 1;
                b = (byte)encrypted.ReadByte();
                encrypted.Position = encrypted.Length - 1;
                encrypted.WriteByte((byte)(~b));
                encrypted.Close();
                encrypted = null;

                ExtendedAssert.Throws <CryptographicException>(
                    () =>
                {
                    secure = new SecureFile(encryptName, SecureFileMode.Decrypt, privateKey);
                    secure.DecryptTo(decryptName);
                });
            }
            finally
            {
                if (original != null)
                {
                    original.Close();
                }

                if (encrypted != null)
                {
                    encrypted.Close();
                }

                try { System.IO.File.Delete(originalName); } catch { }
                try { System.IO.File.Delete(encryptName); } catch { }
                try { System.IO.File.Delete(decryptName); } catch { }
            }
        }
Example #10
0
        public void Package_AddFile()
        {
            Package              package;
            EnhancedStream       fs;
            EnhancedMemoryStream es = new EnhancedMemoryStream();
            PackageEntry         entry;

            byte[] buf;
            string inputFile;
            string outputFile;

            inputFile  = Path.GetTempFileName();
            outputFile = Path.GetTempFileName();
            try
            {
                buf = new byte[37000];
                for (int i = 0; i < buf.Length; i++)
                {
                    buf[i] = (byte)i;
                }

                fs = new EnhancedFileStream(inputFile, FileMode.OpenOrCreate);
                fs.WriteBytes32(buf);
                fs.Close();

                //-------------------------

                package = new Package();
                package.Create(es);

                entry = package.AddFile("/Foo/Bar/Test1.dat", inputFile);
                Assert.IsTrue(entry.IsFile);
                Assert.IsTrue(package["/Foo"].IsFolder);
                Assert.IsTrue(package["/Foo/Bar"].IsFolder);
                Assert.IsTrue(package["/Foo/Bar/Test1.dat"].IsFile);

                package.Close(true);

                //-------------------------

                package = new Package(es);

                Assert.IsTrue(entry.IsFile);
                Assert.IsTrue(package["/Foo"].IsFolder);
                Assert.IsTrue(package["/Foo/Bar"].IsFolder);
                Assert.IsTrue(package["/Foo/Bar/Test1.dat"].IsFile);

                package["/Foo/Bar/Test1.dat"].GetContents(outputFile);

                fs = new EnhancedFileStream(outputFile, FileMode.Open);
                try
                {
                    CollectionAssert.AreEqual(buf, fs.ReadBytes32());
                }
                finally
                {
                    fs.Close();
                }

                package.Close();
            }
            finally
            {
                File.Delete(inputFile);
                File.Delete(outputFile);
            }
        }
Example #11
0
        /// <summary>
        /// Executes the specified UNZIP command.
        /// </summary>
        /// <param name="args">The command arguments.</param>
        /// <returns>0 on success, a non-zero error code otherwise.</returns>
        public static int Execute(string[] args)
        {
            const string usage =
                @"
Usage: 

-------------------------------------------------------------------------------
vegomatic unzip [-o:<path>] [-r] [-fn] <pattern>

Unzips the specified files to the current directory.

    -o:<path>   specifies the folder where extracted files will
                be written.  Files will be written to the current
                directory if this option is not present.

    -r          indicates that the file pattern
                should be searched recursively.

    -fn         indicates that zip files will be extracted
                to a folder named by the zip archive file.

    <pattern>   specifies the wildcarded pattern for the
                files to be extracted.

";
            bool   recursive  = false;
            bool   folderName = false;
            string outFolder  = Environment.CurrentDirectory;
            string pattern;

            string[] files;
            int      cExtracted;

            if (args.Length < 1)
            {
                Program.Error(usage);
                return(1);
            }

            for (int i = 0; i < args.Length - 1; i++)
            {
                string arg = args[i];

                if (arg.StartsWith("-o:"))
                {
                    outFolder = Path.GetFullPath(arg.Substring(3));
                }
                else if (arg == "-r")
                {
                    recursive = true;
                }
                else if (arg == "-fn")
                {
                    folderName = true;
                }
                else
                {
                    Program.Error(usage);
                    return(1);
                }
            }

            pattern = args[args.Length - 1];
            files   = Helper.GetFilesByPattern(pattern, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);

            cExtracted = 0;
            Program.Output("[{0}] files found.", files.Length);

            foreach (string file in files)
            {
                ZipFile archive = null;
                string  outPath;

                try
                {
                    archive = new ZipFile(file);
                    outPath = Helper.AddTrailingSlash(outFolder);

                    if (folderName)
                    {
                        outPath += Helper.AddTrailingSlash(Helper.GetFileNameWithoutExtension(file));
                    }

                    foreach (ZipEntry entry in archive)
                    {
                        Stream         inStream  = null;
                        EnhancedStream outStream = null;
                        string         outFile;

                        outFile = outPath + entry.Name;
                        Helper.CreateFileTree(outFile);

                        Program.Output("Extract: {0}", entry.Name);

                        try
                        {
                            inStream  = archive.GetInputStream(entry);
                            outStream = new EnhancedFileStream(outFile, FileMode.Create, FileAccess.ReadWrite);

                            outStream.CopyFrom(inStream, -1);
                            cExtracted++;
                        }
                        finally
                        {
                            if (inStream != null)
                            {
                                inStream.Close();
                            }

                            if (outStream != null)
                            {
                                outStream.Close();
                            }

                            File.SetCreationTime(outFile, entry.DateTime);
                            File.SetLastWriteTime(outFile, entry.DateTime);
                        }
                    }
                }
                catch (Exception e)
                {
                    Program.Error("{0}: {1}", e.Message, file);
                }
                finally
                {
                    if (archive != null)
                    {
                        archive.Close();
                    }
                }
            }

            Program.Output("[{0}] files extracted from [{1}] zip archives.", cExtracted, files.Length);

            return(0);
        }