Beispiel #1
0
        public static bool hash_comparefile(String fileName1, String fileName2)
        {
            System.Security.Cryptography.HashAlgorithm hash = System.Security.Cryptography.HashAlgorithm.Create();

            byte[] fileHash1;
            byte[] fileHash2 = null;

            void SecondHash()
            {
                using (FileStream fileStream2 = new FileStream(fileName2, FileMode.Open)) fileHash2 = hash.ComputeHash(fileStream2);
            }

            bool samedrive = fileName1.Substring(0, 1) == fileName2.Substring(0, 1);

            Task task = null;


            if (samedrive)
            {
                SecondHash();
            }
            else
            {
                task = Task.Factory.StartNew(SecondHash);
            }

            using (FileStream fileStream1 = new FileStream(fileName1, FileMode.Open)) fileHash1 = hash.ComputeHash(fileStream1);


            if (!samedrive)
                task.Wait(); }
Beispiel #2
0
        // TODO: should this function follow the, apparent, dodSON.Core pattern of putting functions like this into ...Helper classes?

        /// <summary>
        /// Generates the Password Salt Result Hash.
        /// </summary>
        /// <param name="hashAlgorithm">The required <see cref="System.Security.Cryptography.HashAlgorithm"/>.</param>
        /// <param name="password">The password.</param>
        /// <param name="salt">The salt.</param>
        /// <returns>The generated Password Salt Result Hash.</returns>
        public static byte[] ComputeResult(System.Security.Cryptography.HashAlgorithm hashAlgorithm,
                                           System.Security.SecureString password,
                                           byte[] salt)
        {
            // merge salt and password
            byte[] saltedPassword = new byte[salt.Length + password.Length];
            byte[] passwordArray  = null;
            try
            {
                // add the salt
                for (int i = 0; i < salt.Length; i++)
                {
                    saltedPassword[i] = salt[i];
                }
                // extract the password
                passwordArray = CryptographyHelper.SecureStringToByteArray(password);
                // add the password
                for (int i = 0; i < passwordArray.Length; i++)
                {
                    saltedPassword[salt.Length + i] = passwordArray[i];
                }
                // return result hash
                return(hashAlgorithm.ComputeHash(saltedPassword));
            }
            finally
            {
                // clean up
                Array.Clear(saltedPassword, 0, saltedPassword.Length);
                Array.Clear(passwordArray, 0, passwordArray.Length);
            }
        }
Beispiel #3
0
        private bool IsHashValid()
        {
            // first, validate the actual hash chosen
            bool valid = comboBoxHash.Items.Contains(comboBoxHash.Text);

            // second, for keyed hash algorithms only, validate the key
            using (System.Security.Cryptography.HashAlgorithm hash = System.Security.Cryptography.HashAlgorithm.Create(comboBoxHash.Text))
            {
                if (hash != null)
                {
                    if (hash.GetType().IsSubclassOf(typeof(System.Security.Cryptography.KeyedHashAlgorithm)))
                    {
                        byte[] key = System.Text.Encoding.ASCII.GetBytes(textBoxHashKey.Text);

                        // MACTripleDES is a special case that only accepts a key that is 16 or 20 bytes long
                        // and must not be "weak" as determined by the library
                        if (hash is System.Security.Cryptography.MACTripleDES)
                        {
                            valid = (key.Length == 16 || key.Length == 24) && !System.Security.Cryptography.TripleDES.IsWeakKey(key);
                        }
                        // all other keyed hashes only require non empty keys
                        else
                        {
                            valid = !string.IsNullOrEmpty(textBoxHashKey.Text);
                        }
                    }
                }
                else
                {
                    valid = false;
                }
            }

            return(valid);
        }
Beispiel #4
0
        private System.Security.Cryptography.HashAlgorithm alg;   // used for comparing text values

        public RichTextBoxEx()
        {
            charFormat = new User32.CHARFORMAT()
            {
                cbSize     = Marshal.SizeOf(typeof(User32.CHARFORMAT)),
                szFaceName = new char[32]
            };

            lParam1 = Marshal.AllocCoTaskMem(charFormat.cbSize);

            // defaults
            NumberFont = new System.Drawing.Font("Consolas",
                                                 9.75F,
                                                 System.Drawing.FontStyle.Regular,
                                                 System.Drawing.GraphicsUnit.Point, ((byte)(0)));

            NumberColor           = Color.FromName("DarkGray");
            NumberLineCounting    = LineCounting.CRLF;
            NumberAlignment       = StringAlignment.Center;
            NumberBorder          = SystemColors.ControlDark;
            NumberBorderThickness = 1;
            NumberPadding         = 2;
            NumberBackground1     = SystemColors.ControlLight;
            NumberBackground2     = SystemColors.Window;
            SetStringDrawingFormat();

            alg = System.Security.Cryptography.SHA1.Create();
        }
Beispiel #5
0
        private static string MD5(string password)
        {
            //byte[] textBytes = Encoding.UTF8.GetBytes(password);
            //try
            //{
            //    System.Security.Cryptography.MD5CryptoServiceProvider cryptHandler;
            //    cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider();
            //    byte[] hash = cryptHandler.ComputeHash(textBytes);
            //    string ret = "";
            //    foreach (byte a in hash)
            //    {
            //        ret += a.ToString("x2");
            //    }
            //    return ret;
            //}
            //catch
            //{
            //    throw;
            //}
            try
            {
                System.Security.Cryptography.HashAlgorithm hash = System.Security.Cryptography.MD5.Create();
                byte[] hash_out = hash.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));

                var md5_str = BitConverter.ToString(hash_out).Replace("-", "");
                return(md5_str.ToLower());
            }
            catch
            {
                throw;
            }
        }
 byte[] CalculateHash(String filePath, System.Security.Cryptography.HashAlgorithm hashAlgorithm)
 {
     using (FileStream stream = File.OpenRead(filePath))
     {
         return(hashAlgorithm.ComputeHash(stream));
     }
 }
 public HashCalculatingStream(System.IO.Stream basestream, System.Security.Cryptography.HashAlgorithm algorithm)
     : base(basestream)
 {
     m_hash = algorithm;
     m_hash.Initialize();
     m_hashbuffer = new byte[m_hash.InputBlockSize];
 }
Beispiel #8
0
        public BackupHandler(string backendurl, Options options, BackupResults results)
        {
            EMPTY_METADATA = Utility.WrapMetadata(new Dictionary<string, string>(), options);

            m_options = options;
            m_result = results;
            m_backendurl = backendurl;

            m_attributeFilter = m_options.FileAttributeFilter;
            m_symlinkPolicy = m_options.SymlinkPolicy;
            m_blocksize = m_options.Blocksize;

            m_blockbuffer = new byte[m_options.Blocksize * Math.Max(1, m_options.FileReadBufferSize / m_options.Blocksize)];
            m_blocklistbuffer = new byte[m_options.Blocksize];

            m_blockhasher = System.Security.Cryptography.HashAlgorithm.Create(m_options.BlockHashAlgorithm);
            m_filehasher = System.Security.Cryptography.HashAlgorithm.Create(m_options.FileHashAlgorithm);

            if (m_blockhasher == null)
                throw new Exception(string.Format(Strings.Foresthash.InvalidHashAlgorithm, m_options.BlockHashAlgorithm));
            if (m_filehasher == null)
                throw new Exception(string.Format(Strings.Foresthash.InvalidHashAlgorithm, m_options.FileHashAlgorithm));

            if (!m_blockhasher.CanReuseTransform)
                throw new Exception(string.Format(Strings.Foresthash.InvalidCryptoSystem, m_options.BlockHashAlgorithm));
            if (!m_filehasher.CanReuseTransform)
                throw new Exception(string.Format(Strings.Foresthash.InvalidCryptoSystem, m_options.FileHashAlgorithm));

            if (options.AllowPassphraseChange)
                throw new Exception(Strings.Foresthash.PassphraseChangeUnsupported);
        }
Beispiel #9
0
        //These two functions used for calculating hash of Header object
        //GetFullHashBytes includes all fields in calculation, while GetSimpleHashBytes considers only two: Nonce and Datahash
        //This is done to decouple the key from the object and make it work separately
        //Otherwise including in the file data reference to its header would be impossible, leading to the infinite recursion.


        public static byte[] GetFullHashBytes(this HeaderModel header)
        {
            using (System.Security.Cryptography.HashAlgorithm sha256 = System.Security.Cryptography.SHA256.Create())
            {
                return(sha256.ComputeHash(Encoding.UTF8.GetBytes(header.Serialize())));
            }
        }
Beispiel #10
0
        public byte[] GetAssemblyHash()
        {
            System.Security.Cryptography.HashAlgorithm HA = System.Security.Cryptography.SHA256.Create();

            try
            {
                byte[] b;
                using (System.IO.FileStream fs = new System.IO.FileStream(GetAssemblyPath(), System.IO.FileMode.Open, System.IO.FileAccess.Read))
                    b = HA.ComputeHash(fs);
                return(b);
            }
            catch
            {
                return(null);
                //Random r = new Random();
                //int keyLen = 128;
                //byte[] b = new byte[keyLen];
                //r.NextBytes(b);
                //return b;
            }
            finally
            {
                HA.Dispose();
            }
        }
        public IndexerSetupResult Setup(IXDescriptor descriptor)
        {
            if (setup)
            {
                return(IndexerSetupResult.Failure);
            }

            hashFactory = new System.Security.Cryptography.SHA256Managed();

            string _v = Convert.ToBase64String(hashFactory.ComputeHash(System.Text.UTF8Encoding.UTF8.GetBytes(descriptor.ToString())));

            int df = indexSearcher.DocFreq(new Term(indexerDocumentDescriptorVersion, _v));

            // set up searcher
            TermDocs term = indexSearcher.IndexReader.TermDocs();

            List <Document> docs = new List <Document>();

            while (term.Next())
            {
                docs.Add(indexSearcher.Doc(term.Doc));
            }

            return(IndexerSetupResult.Okay);
        }
        private void verifyTask_RunTask(object param, ref object result)
        {
            byte[] buffer;
            byte[] oldBuffer;
            int    bytesRead;
            int    oldBytesRead;
            long   size;
            long   totalBytesRead = 0;

            using (Stream stream = File.OpenRead(_fileName)) //Change to MD5.Create for MD5 verification
                using (System.Security.Cryptography.HashAlgorithm hashAlgorithm = System.Security.Cryptography.SHA1.Create())
                {
                    size = stream.Length;

                    buffer = new byte[4096];

                    bytesRead       = stream.Read(buffer, 0, buffer.Length);
                    totalBytesRead += bytesRead;

                    do
                    {
                        if (_verifyTask.Cancelled)
                        {
                            return;
                        }

                        oldBytesRead = bytesRead;
                        oldBuffer    = buffer;

                        buffer    = new byte[4096];
                        bytesRead = stream.Read(buffer, 0, buffer.Length);

                        totalBytesRead += bytesRead;

                        if (bytesRead == 0)
                        {
                            hashAlgorithm.TransformFinalBlock(oldBuffer, 0, oldBytesRead);
                        }
                        else
                        {
                            hashAlgorithm.TransformBlock(oldBuffer, 0, oldBytesRead, oldBuffer, 0);
                        }

                        if (this.IsHandleCreated)
                        {
                            this.BeginInvoke(new MethodInvoker(() =>
                            {
                                int value = (int)((double)totalBytesRead * 100 / size);

                                if (value >= this.progressDownload.Minimum && value <= this.progressDownload.Maximum)
                                {
                                    this.progressDownload.Value = value;
                                }
                            }));
                        }
                    } while (bytesRead != 0);

                    result = hashAlgorithm.Hash;
                }
        }
Beispiel #13
0
 public override byte[] encodeAsBuffer(byte[] data, int version)
 {
     if (!(data != null))
     {
         return(null);
     }
     System.Security.Cryptography.HashAlgorithm hashAlgorithm = null;
     if (capex.crypto.SHAEncoder.SHA1 == version)
     {
         hashAlgorithm = System.Security.Cryptography.SHA1.Create();
     }
     else if (capex.crypto.SHAEncoder.SHA256 == version)
     {
         hashAlgorithm = System.Security.Cryptography.SHA256.Create();
     }
     else if (capex.crypto.SHAEncoder.SHA384 == version)
     {
         hashAlgorithm = System.Security.Cryptography.SHA384.Create();
     }
     else if (capex.crypto.SHAEncoder.SHA512 == version)
     {
         hashAlgorithm = System.Security.Cryptography.SHA512.Create();
     }
     if (!(hashAlgorithm != null))
     {
         return(null);
     }
     return(hashAlgorithm.ComputeHash(data));
 }
Beispiel #14
0
        byte[] BuildAuthenticationData()
        {
            Contract.Ensures(Contract.Result <byte[]>() != null ||
                             mFooter.Authentication == BlobTransportStreamAuthentication.None);
            Contract.Assert(mFooterPosition.IsNotNone());

            System.Security.Cryptography.HashAlgorithm hash_algo = null;
            switch (mFooter.Authentication)
            {
            case BlobTransportStreamAuthentication.None: break;

            // #TODO_IMPLEMENT:
            case BlobTransportStreamAuthentication.Crc: throw new NotImplementedException();

            case BlobTransportStreamAuthentication.Hash: throw new NotImplementedException();

            case BlobTransportStreamAuthentication.Rsa: throw new NotImplementedException();
            }

            if (hash_algo != null)
            {
                return(hash_algo.ComputeHash(BaseStream, StartPosition, mFooterPosition));
            }

            return(null);
        }
Beispiel #15
0
        /// <summary>
        /// 获取文件Hash值,如果文件正在使用中,则会报错
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="NullValue"></param>
        /// <returns></returns>
        public static string GetFileHash(string fileName, string NullValue)
        {
            string result = NullValue;

            if (System.IO.File.Exists(fileName))
            {
                lock (lockObject)
                {
                    try
                    {
                        using (System.Security.Cryptography.HashAlgorithm ah = System.Security.Cryptography.HashAlgorithm.Create())
                        {
                            using (FileStream fs = new FileStream(fileName, FileMode.Open))
                            {
                                result = All.Class.Num.Hex2Str(ah.ComputeHash(fs));
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        All.Class.Error.Add(e);
                    }
                }
            }
            return(result);
        }
Beispiel #16
0
        /// <summary>
        /// 获取指定文件的版本
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string GetFileCode(string fileName, string NullValue)
        {
            string result = NullValue;

            if (System.IO.File.Exists(fileName))
            {
                lock (lockObject)
                {
                    if (fileName.ToUpper().IndexOf(".exe".ToUpper()) > 0 || fileName.ToUpper().IndexOf(".dll".ToUpper()) > 0)
                    {
                        System.Diagnostics.FileVersionInfo fi = System.Diagnostics.FileVersionInfo.GetVersionInfo(fileName);
                        result = fi.FileVersion;
                    }
                    else
                    {
                        using (System.Security.Cryptography.HashAlgorithm ah = System.Security.Cryptography.HashAlgorithm.Create())
                        {
                            using (FileStream fs = new FileStream(fileName, FileMode.Open))
                            {
                                result = All.Class.Num.Hex2Str(ah.ComputeHash(fs));
                            }
                        }
                    }
                }
            }
            return(result);
        }
Beispiel #17
0
 public string GetHash(string m_strSource)
 {
     System.Security.Cryptography.HashAlgorithm hashAlgorithm = System.Security.Cryptography.HashAlgorithm.Create("MD5");
     byte[] bytes   = System.Text.Encoding.UTF8.GetBytes(m_strSource);
     byte[] inArray = hashAlgorithm.ComputeHash(bytes);
     return(System.Convert.ToBase64String(inArray));
 }
        /// <summary>
        /// Determine an unique identifier that specify the linked shader program.
        /// </summary>
        /// <param name="cctx">
        /// A <see cref="ShaderCompilerContext"/> determining the compiler parameteres.
        /// </param>
        /// <param name="libraryId">
        /// A <see cref="String"/> that identifies the shader object in library.
        /// </param>
        /// <returns>
        /// It returns a string that identify the a shader program classified with <paramref name="libraryId"/> by
        /// specifying <paramref name="cctx"/> as compiled parameters.
        /// </returns>
        internal static string ComputeLibraryHash(ShaderCompilerContext cctx, string libraryId)
        {
            StringBuilder hashMessage = new StringBuilder();

            // Take into account the shader program name
            hashMessage.Append(libraryId);
            // Take into account the shader version
            hashMessage.Append(cctx.ShaderVersion);

            // Do NOT take into account the shader program compilation symbols: they are considered
            // in attached shader objects.

            // Take into account the shader program include paths
            foreach (string includePath in cctx.Includes)
            {
                hashMessage.AppendFormat("{0}", includePath);
            }

            // Hash all information
            byte[] hashBytes;
            using (System.Security.Cryptography.HashAlgorithm hash = System.Security.Cryptography.HashAlgorithm.Create("SHA256")) {
                hashBytes = hash.ComputeHash(Encoding.ASCII.GetBytes(hashMessage.ToString()));
            }

            // ConvertItemType has to string
            return(Convert.ToBase64String(hashBytes));
        }
        /// <summary>
        /// Return the MD5 of the whole item data
        /// </summary>
        /// <returns></returns>
        public string MD5()
        {
            if (CompleteDataStream != null)
            {
                return(CompleteDataStream.MD5());
            }
            else
            {
                lock (dataLocker)
                {
                    using (System.Security.Cryptography.HashAlgorithm md5 = System.Security.Cryptography.MD5.Create())
                    {
                        byte[] chunkBytes;
                        for (int i = 0; i < ChunkDataStreams.Length; i++)
                        {
                            chunkBytes = ChunkDataStreams[i].ToArray();

                            if (i < ChunkDataStreams.Length - 1)
                            {
                                md5.TransformBlock(chunkBytes, 0, chunkBytes.Length, chunkBytes, 0);
                            }
                            else
                            {
                                md5.TransformFinalBlock(chunkBytes, 0, chunkBytes.Length);
                            }
                        }

                        return(BitConverter.ToString(md5.Hash).Replace("-", ""));
                    }
                }
            }
        }
Beispiel #20
0
        //// NOTE: Leave out the finalizer altogether if this class doesn't
        //// own unmanaged resources itself, but leave the other methods
        //// exactly as they are.
        //~Encryption()
        //{
        //    // Finalizer calls Dispose(false)
        //    Dispose(false);
        //}

        // The bulk of the clean-up code is implemented in Dispose(bool)
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                // Free managed resources.
                lock (MacProviderLock)
                {
                    if (_MacProvider != null)
                    {
                        _MacProvider.Dispose();
                        _MacProvider = null;
                    }
                }
                lock (RsaProviderLock)
                {
                    if (_RsaProvider != null)
                    {
                        _RsaProvider.Dispose();
                        _RsaProvider = null;
                    }
                }
                if (_RsaSignatureHashAlgorithm != null)
                {
                    _RsaSignatureHashAlgorithm.Dispose();
                    _RsaSignatureHashAlgorithm = null;
                }
            }
        }
Beispiel #21
0
 public string MD5(string source)
 {
     System.Security.Cryptography.HashAlgorithm hashAlgorithm = System.Security.Cryptography.HashAlgorithm.Create("MD5");
     byte[] bytes = System.Text.Encoding.UTF8.GetBytes(source);
     byte[] value = hashAlgorithm.ComputeHash(bytes);
     return(System.BitConverter.ToString(value));
 }
Beispiel #22
0
        public static byte[] ComputeHash(System.Security.Cryptography.HashAlgorithm algorithm, byte[] inputBytes)
        {
            // calculate hash from inputBytes using provided algorithm
            byte[] hash = algorithm.ComputeHash(inputBytes);

            return(hash);
        }
Beispiel #23
0
 static FSDirectory()
 {
     {
         try
         {
             System.String name = SupportClass.AppSettings.Get("Lucene.Net.FSDirectory.class", typeof(FSDirectory).FullName);
             IMPL = System.Type.GetType(name);
         }
         catch (System.Security.SecurityException)
         {
             try
             {
                 IMPL = System.Type.GetType(typeof(FSDirectory).FullName);
             }
             catch (System.Exception e)
             {
                 throw new System.SystemException("cannot load default FSDirectory class: " + e.ToString(), e);
             }
         }
         catch (System.Exception e)
         {
             throw new System.SystemException("cannot load FSDirectory class: " + e.ToString(), e);
         }
     }
     {
         try
         {
             DIGESTER = SupportClass.Cryptography.GetHashAlgorithm();
         }
         catch (System.Exception e)
         {
             throw new System.SystemException(e.ToString(), e);
         }
     }
 }
 public HashCalculatingStream(System.IO.Stream basestream, System.Security.Cryptography.HashAlgorithm algorithm)
     : base(basestream)
 {
     m_hash = algorithm;
     m_hash.Initialize();
     m_hashbuffer = new byte[m_hash.InputBlockSize];
 }
Beispiel #25
0
        /// <summary>
        /// Will read the <paramref name="length"/> number of bytes from the given stream, then convert that byte array into a hash.
        /// </summary>
        /// <param name="source">The stream to read bytes from.</param>
        /// <param name="length">The number of bytes to read from the stream.</param>
        /// <param name="hashProvider">The <see cref="System.Security.Cryptography.HashAlgorithm"/> used to compute the hash.</param>
        /// <returns>A byte array containing the hash.</returns>
        public static byte[] ComputeHash(System.IO.Stream source,
                                         int length,
                                         System.Security.Cryptography.HashAlgorithm hashProvider)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (!source.CanRead)
            {
                throw new ArgumentException("The parameter source represents an unreadable stream.", "source");
            }
            if (length < 0)
            {
                throw new ArgumentException("The parameter length cannot be less than zero. (0 >= length)", "length");
            }
            if (hashProvider == null)
            {
                throw new ArgumentNullException("hashProvider");
            }
            var buffer = new byte[length];

            source.Read(buffer, 0, length);
            return(ComputeHash(buffer, hashProvider));
        }
 private void CheckCopy(string destination, string source, FileSystemEventArgs e = null)
 {
     if (File.Exists(destination)) //Checks is file exists
     {
         System.Security.Cryptography.HashAlgorithm ha = System.Security.Cryptography.HashAlgorithm.Create();
         using (FileStream f1 = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite),
                f2 = new FileStream(destination, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
         {
             /* Calculate Hash */
             byte[] hash1 = ha.ComputeHash(f1);
             byte[] hash2 = ha.ComputeHash(f2);
             //Compare files and copy if destination does not match server
             if (BitConverter.ToString(hash1) != BitConverter.ToString(hash2))
             {
                 log.Info("New Database version detected in ", sourceDBpath);
                 log.Debug("Copy [{0}] To [{1}]", source, destination);
                 File.Copy(source, destination, true);
                 OnDataBaseUpdate(e);
             }
             else
             {
                 log.Debug("Remote DB matches current copy");
             }
         }
     }
     else //copies if no destination file/
     {
         log.Warn("Database missing: {0} ", destination);
         log.Debug("Copy [{0}] To [{1}]", source, destination);
         File.Copy(source, destination, true);
     }
 }
 internal static ImmutableArray <byte> CalculateChecksum(byte[] buffer, int offset, int count, SourceHashAlgorithm algorithmId)
 {
     using (System.Security.Cryptography.HashAlgorithm algorithm = CryptographicHashProvider.TryGetAlgorithm(algorithmId))
     {
         Debug.Assert(algorithm != null);
         return(ImmutableArray.Create(algorithm.ComputeHash(buffer, offset, count)));
     }
 }
Beispiel #28
0
        public Boolean Save(IChainStorageProvider StorageProvider, System.Security.Cryptography.HashAlgorithm _HashAlgorithm)
        {
            TimeStamp = DateTime.Now;
            this.PreviousBlockHash = StorageProvider.PopBlock()?.BlockHash;
            this.BlockHash         = _generateHashOfSelf(_HashAlgorithm);

            return(StorageProvider.Add(this));
        }
Beispiel #29
0
 private static System.Security.Cryptography.HashAlgorithm CreateHashAlgorithm()
 {
     if (hash == null)
     {
         hash = System.Security.Cryptography.SHA1.Create();
     }
     return(hash);
 }
        public void EnsureInputUnchangedTest(string name, Type expectedType)
        {
            System.Security.Cryptography.HashAlgorithm hasher = HashAlgorithm.Create(name);
            byte[] originalInput = (byte[])TestVectors.Battery.NumericRepeated.Clone();
            byte[] input         = (byte[])TestVectors.Battery.NumericRepeated.Clone();

            byte[] output = hasher.ComputeHash(input);
            CustomAssert.AreEqual(originalInput, input);
        }
Beispiel #31
0
        internal static void Dispose(this System.Security.Cryptography.HashAlgorithm algorithm)
        {
            if (algorithm == null)
            {
                throw new NullReferenceException();
            }

            algorithm.Clear();
        }
Beispiel #32
0
        public ulong HashImageData(System.Security.Cryptography.HashAlgorithm hashAlgorithm)
        {
            ulong metaHash = unchecked ((ulong)Width * 4551534108298448059ul + (ulong)Height * 7310107420406914801ul); // two random primes

            byte[] dataHashArr = hashAlgorithm.ComputeHash(_data);
            ulong  dataHash    = BitConverter.ToUInt64(dataHashArr, 0);

            return(dataHash ^ metaHash);
        }
Beispiel #33
0
        public HashCryptoBuildIn(System.Security.Cryptography.HashAlgorithm a_hash_algorithm, int a_block_size)
            : base(a_hash_algorithm.HashSize / 8, a_block_size)
        {
            if (a_hash_algorithm.CanReuseTransform == false)
                throw new NotImplementedException();
            if (a_hash_algorithm.CanTransformMultipleBlocks == false)
                throw new NotImplementedException();

            m_hash_algorithm = a_hash_algorithm;
        }
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (m_hash != null)
            {
                m_hash.Clear();
                m_hash = null;

                m_hashbuffer = null;
                m_hashbufferLength = 0;
            }
        }
Beispiel #35
0
        public void Run(string[] sources, Library.Utility.IFilter filter)
        {
            m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_Begin);                        
            
            using(m_database = new LocalBackupDatabase(m_options.Dbpath, m_options))
            {
                m_result.SetDatabase(m_database);
                m_result.Dryrun = m_options.Dryrun;

                Utility.UpdateOptionsFromDb(m_database, m_options);
                Utility.VerifyParameters(m_database, m_options);

                if (m_database.RepairInProgress)
                    throw new Exception("The database was attempted repaired, but the repair did not complete. This database may be incomplete and the backup process cannot continue. You may delete the local database and attempt to repair it again.");

                m_blocksize = m_options.Blocksize;

                m_blockbuffer = new byte[m_options.Blocksize * Math.Max(1, m_options.FileReadBufferSize / m_options.Blocksize)];
                m_blocklistbuffer = new byte[m_options.Blocksize];

                m_blockhasher = System.Security.Cryptography.HashAlgorithm.Create(m_options.BlockHashAlgorithm);
                m_filehasher = System.Security.Cryptography.HashAlgorithm.Create(m_options.FileHashAlgorithm);

                if (m_blockhasher == null)
                    throw new Exception(Strings.Common.InvalidHashAlgorithm(m_options.BlockHashAlgorithm));
                if (m_filehasher == null)
                    throw new Exception(Strings.Common.InvalidHashAlgorithm(m_options.FileHashAlgorithm));

                if (!m_blockhasher.CanReuseTransform)
                    throw new Exception(Strings.Common.InvalidCryptoSystem(m_options.BlockHashAlgorithm));
                if (!m_filehasher.CanReuseTransform)
                    throw new Exception(Strings.Common.InvalidCryptoSystem(m_options.FileHashAlgorithm));

                m_database.VerifyConsistency(null, m_options.Blocksize, m_options.BlockhashSize);
                // If there is no filter, we set an empty filter to simplify the code
                // If there is a filter, we make sure that the sources are included
                m_filter = filter ?? new Library.Utility.FilterExpression();
                m_sourceFilter = new Library.Utility.FilterExpression(sources, true);
            	
                m_backendLogFlushTimer = DateTime.Now.Add(FLUSH_TIMESPAN);
                System.Threading.Thread parallelScanner = null;

    
                try
                {

                    using(var backend = new BackendManager(m_backendurl, m_options, m_result.BackendWriter, m_database))
                    using(var filesetvolume = new FilesetVolumeWriter(m_options, m_database.OperationTimestamp))
                    {
                        using(var snapshot = GetSnapshot(sources, m_options, m_result))
                        {
                            // Start parallel scan
                            if (m_options.ChangedFilelist == null || m_options.ChangedFilelist.Length < 1)
                            {
                                parallelScanner = new System.Threading.Thread(CountFilesThread) {
                                    Name = "Read ahead file counter",
                                    IsBackground = true
                                };
                                parallelScanner.Start(snapshot);
                            }

                            PreBackupVerify(backend);

                            // Verify before uploading a synthetic list
                            m_database.VerifyConsistency(null, m_options.Blocksize, m_options.BlockhashSize);
                            UploadSyntheticFilelist(backend);

                            m_database.BuildLookupTable(m_options);
                            m_transaction = m_database.BeginTransaction();

                            var repcnt = 0;
                            while(repcnt < 100 && m_database.GetRemoteVolumeID(filesetvolume.RemoteFilename) >= 0)
                                filesetvolume.ResetRemoteFilename(m_options, m_database.OperationTimestamp.AddSeconds(repcnt++));
        		            
                            if (m_database.GetRemoteVolumeID(filesetvolume.RemoteFilename) >= 0)
                                throw new Exception("Unable to generate a unique fileset name");

                            m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_ProcessingFiles);
                            var filesetvolumeid = m_database.RegisterRemoteVolume(filesetvolume.RemoteFilename, RemoteVolumeType.Files, RemoteVolumeState.Temporary, m_transaction);
                            m_database.CreateFileset(filesetvolumeid, VolumeBase.ParseFilename(filesetvolume.RemoteFilename).Time, m_transaction);
        	
                            RunMainOperation(snapshot, backend);

                            //If the scanner is still running for some reason, make sure we kill it now 
                            if (parallelScanner != null && parallelScanner.IsAlive)
                                parallelScanner.Abort();
                        }

                        var lastVolumeSize = FinalizeRemoteVolumes(backend);
    		            
                        using(new Logging.Timer("UpdateChangeStatistics"))
                            m_database.UpdateChangeStatistics(m_result);
                        using(new Logging.Timer("VerifyConsistency"))
                            m_database.VerifyConsistency(m_transaction, m_options.Blocksize, m_options.BlockhashSize);
    
                        UploadRealFileList(backend, filesetvolume);
    									
                        m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_WaitForUpload);
                        using(new Logging.Timer("Async backend wait"))
                            backend.WaitForComplete(m_database, m_transaction);
                            
                        if (m_result.TaskControlRendevouz() != TaskControlState.Stop) 
                            CompactIfRequired(backend, lastVolumeSize);
    		            
                        if (m_options.UploadVerificationFile)
                        {
                            m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_VerificationUpload);
                            FilelistProcessor.UploadVerificationFile(backend.BackendUrl, m_options, m_result.BackendWriter, m_database, m_transaction);
                        }

                        if (m_options.Dryrun)
                        {
                            m_transaction.Rollback();
                            m_transaction = null;
                        }
                        else
                        {
                            using(new Logging.Timer("CommitFinalizingBackup"))
                                m_transaction.Commit();
                                
                            m_transaction = null;
                            m_database.Vacuum();
                            
                            if (m_result.TaskControlRendevouz() != TaskControlState.Stop && !m_options.NoBackendverification)
                            {
                                PostBackupVerification();
                            }

                        }
                        
                        m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_Complete);
                        m_database.WriteResults();                    
                        m_database.PurgeLogData(m_options.LogRetention);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    m_result.AddError("Fatal error", ex);
                    throw;
                }
                finally
                {
                    if (parallelScanner != null && parallelScanner.IsAlive)
                    {
                        parallelScanner.Abort();
                        parallelScanner.Join(500);
                        if (parallelScanner.IsAlive)
                            m_result.AddWarning("Failed to terminate filecounter thread", null);
                    }
                
                    if (m_transaction != null)
                        try { m_transaction.Rollback(); }
                        catch (Exception ex) { m_result.AddError(string.Format("Rollback error: {0}", ex.Message), ex); }
                }
            }
        }
Beispiel #36
0
 public HashAlgorithm(System.Security.Cryptography.HashAlgorithm algorithm)
 {
     _algorithm = algorithm;
 }
Beispiel #37
0
 static FSDirectory()
 {
     {
         try
         {
             System.String name = SupportClass.AppSettings.Get("Lucene.Net.FSDirectory.class", typeof(SimpleFSDirectory).FullName);
             if (typeof(FSDirectory).FullName.Equals(name))
             {
                 // FSDirectory will be abstract, so we replace it by the correct class
                 IMPL = typeof(SimpleFSDirectory);
             }
             else
             {
                 IMPL = System.Type.GetType(name);
             }
         }
         catch (System.Security.SecurityException se)
         {
             IMPL = typeof(SimpleFSDirectory);
         }
         catch (System.Exception e)
         {
             throw new System.SystemException("cannot load FSDirectory class: " + e.ToString(), e);
         }
     }
     {
         try
         {
             DIGESTER = SupportClass.Cryptography.GetHashAlgorithm();
         }
         catch (System.Exception e)
         {
             throw new System.SystemException(e.ToString(), e);
         }
     }
     DEFAULT_READ_CHUNK_SIZE = Constants.JRE_IS_64BIT?System.Int32.MaxValue:100 * 1024 * 1024;
 }
Beispiel #38
0
        public void Run(string[] sources, Library.Utility.IFilter filter)
        {
            m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_Begin);

            using(m_database = new LocalBackupDatabase(m_options.Dbpath, m_options))
            {
                m_result.SetDatabase(m_database);
                m_result.Dryrun = m_options.Dryrun;

                Utility.UpdateOptionsFromDb(m_database, m_options);
                Utility.VerifyParameters(m_database, m_options);

                m_blocksize = m_options.Blocksize;

                m_blockbuffer = new byte[m_options.Blocksize * Math.Max(1, m_options.FileReadBufferSize / m_options.Blocksize)];
                m_blocklistbuffer = new byte[m_options.Blocksize];

                m_blockhasher = System.Security.Cryptography.HashAlgorithm.Create(m_options.BlockHashAlgorithm);
                m_filehasher = System.Security.Cryptography.HashAlgorithm.Create(m_options.FileHashAlgorithm);

                if (m_blockhasher == null)
                    throw new Exception(Strings.Foresthash.InvalidHashAlgorithm(m_options.BlockHashAlgorithm));
                if (m_filehasher == null)
                    throw new Exception(Strings.Foresthash.InvalidHashAlgorithm(m_options.FileHashAlgorithm));

                if (!m_blockhasher.CanReuseTransform)
                    throw new Exception(Strings.Foresthash.InvalidCryptoSystem(m_options.BlockHashAlgorithm));
                if (!m_filehasher.CanReuseTransform)
                    throw new Exception(Strings.Foresthash.InvalidCryptoSystem(m_options.FileHashAlgorithm));

                m_database.VerifyConsistency(null, m_options.Blocksize, m_options.BlockhashSize);
                // If there is no filter, we set an empty filter to simplify the code
                // If there is a filter, we make sure that the sources are included
                m_filter = filter ?? new Library.Utility.FilterExpression();
                m_sourceFilter = new Library.Utility.FilterExpression(sources, true);

                var lastVolumeSize = -1L;
                m_backendLogFlushTimer = DateTime.Now.Add(FLUSH_TIMESPAN);
                System.Threading.Thread parallelScanner = null;

                try
                {
                    m_snapshot = GetSnapshot(sources, m_options, m_result);

                    // Start parallel scan
                    if (m_options.ChangedFilelist == null || m_options.ChangedFilelist.Length < 1)
                    {
                        parallelScanner = new System.Threading.Thread(CountFilesThread) {
                            Name = "Read ahead file counter",
                            IsBackground = true
                        };
                        parallelScanner.Start();
                    }

                    using(m_backend = new BackendManager(m_backendurl, m_options, m_result.BackendWriter, m_database))
                    using(m_filesetvolume = new FilesetVolumeWriter(m_options, m_database.OperationTimestamp))
                    {
                        m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_PreBackupVerify);
                        using(new Logging.Timer("PreBackupVerify"))
                        {
                            try
                            {
                                if (m_options.NoBackendverification)
                                    FilelistProcessor.VerifyLocalList(m_backend, m_options, m_database, m_result.BackendWriter);
                                else
                                    FilelistProcessor.VerifyRemoteList(m_backend, m_options, m_database, m_result.BackendWriter);
                            }
                            catch (Exception ex)
                            {
                                if (m_options.AutoCleanup)
                                {
                                    m_result.AddWarning("Backend verification failed, attempting automatic cleanup", ex);
                                    m_result.RepairResults = new RepairResults(m_result);
                                    new RepairHandler(m_backend.BackendUrl, m_options, (RepairResults)m_result.RepairResults).Run();

                                    m_result.AddMessage("Backend cleanup finished, retrying verification");
                                    FilelistProcessor.VerifyRemoteList(m_backend, m_options, m_database, m_result.BackendWriter);
                                }
                                else
                                    throw;
                            }
                        }

                        // Verify before uploading a synthetic list
                        m_database.VerifyConsistency(null, m_options.Blocksize, m_options.BlockhashSize);
                        UploadSyntheticFilelist();

                        m_database.BuildLookupTable(m_options);
                        m_transaction = m_database.BeginTransaction();

                        m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_ProcessingFiles);
                        var filesetvolumeid = m_database.RegisterRemoteVolume(m_filesetvolume.RemoteFilename, RemoteVolumeType.Files, RemoteVolumeState.Temporary, m_transaction);
                        m_database.CreateFileset(filesetvolumeid, VolumeBase.ParseFilename(m_filesetvolume.RemoteFilename).Time, m_transaction);

                        m_blockvolume = new BlockVolumeWriter(m_options);
                        m_blockvolume.VolumeID = m_database.RegisterRemoteVolume(m_blockvolume.RemoteFilename, RemoteVolumeType.Blocks, RemoteVolumeState.Temporary, m_transaction);

                        if (m_options.IndexfilePolicy != Options.IndexFileStrategy.None)
                        {
                            m_indexvolume = new IndexVolumeWriter(m_options);
                            m_indexvolume.VolumeID = m_database.RegisterRemoteVolume(m_indexvolume.RemoteFilename, RemoteVolumeType.Index, RemoteVolumeState.Temporary, m_transaction);
                        }

                        var filterhandler = new FilterHandler(m_snapshot, m_attributeFilter, m_sourceFilter, m_filter, m_symlinkPolicy, m_options.HardlinkPolicy, m_result);

                        using(new Logging.Timer("BackupMainOperation"))
                        {
                            if (m_options.ChangedFilelist != null && m_options.ChangedFilelist.Length >= 1)
                            {
                                m_result.AddVerboseMessage("Processing supplied change list instead of enumerating filesystem");
                                m_result.OperationProgressUpdater.UpdatefileCount(m_options.ChangedFilelist.Length, 0, true);

                                foreach(var p in filterhandler.Mixin(m_options.ChangedFilelist))
                                {
                                    if (m_result.TaskControlRendevouz() == TaskControlState.Stop)
                                    {
                                        m_result.AddMessage("Stopping backup operation on request");
                                        break;
                                    }

                                    try
                                    {
                                        this.HandleFilesystemEntry(p, m_snapshot.GetAttributes(p));
                                    }
                                    catch (Exception ex)
                                    {
                                        m_result.AddWarning(string.Format("Failed to process element: {0}, message: {1}", p, ex.Message), ex);
                                    }
                                }

                                m_database.AppendFilesFromPreviousSet(m_transaction, m_options.DeletedFilelist);
                            }
                            else
                            {
                                foreach(var path in filterhandler.EnumerateFilesAndFolders())
                                {
                                    if (m_result.TaskControlRendevouz() == TaskControlState.Stop)
                                    {
                                        m_result.AddMessage("Stopping backup operation on request");
                                        break;
                                    }

                                    var fa = FileAttributes.Normal;
                                    try { fa = m_snapshot.GetAttributes(path); }
                                    catch { }

                                    this.HandleFilesystemEntry(path, fa);
                                }

                            }

                            //If the scanner is still running for some reason, make sure we kill it now
                            if (parallelScanner != null && parallelScanner.IsAlive)
                                parallelScanner.Abort();

                            // We no longer need to snapshot active
                            try { m_snapshot.Dispose(); }
                            finally { m_snapshot = null; }

                            m_result.OperationProgressUpdater.UpdatefileCount(m_result.ExaminedFiles, m_result.SizeOfExaminedFiles, true);
                        }

                        m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_Finalize);
                        using(new Logging.Timer("FinalizeRemoteVolumes"))
                        {
                            if (m_blockvolume.SourceSize > 0)
                            {
                                lastVolumeSize = m_blockvolume.SourceSize;

                                if (m_options.Dryrun)
                                {
                                    m_result.AddDryrunMessage(string.Format("Would upload block volume: {0}, size: {1}", m_blockvolume.RemoteFilename, Library.Utility.Utility.FormatSizeString(new FileInfo(m_blockvolume.LocalFilename).Length)));
                                    if (m_indexvolume != null)
                                    {
                                        m_blockvolume.Close();
                                        UpdateIndexVolume();
                                        m_indexvolume.FinishVolume(Library.Utility.Utility.CalculateHash(m_blockvolume.LocalFilename), new FileInfo(m_blockvolume.LocalFilename).Length);
                                        m_result.AddDryrunMessage(string.Format("Would upload index volume: {0}, size: {1}", m_indexvolume.RemoteFilename, Library.Utility.Utility.FormatSizeString(new FileInfo(m_indexvolume.LocalFilename).Length)));
                                    }

                                    m_blockvolume.Dispose();
                                    m_blockvolume = null;
                                    m_indexvolume.Dispose();
                                    m_indexvolume = null;
                                }
                                else
                                {
                                    m_database.UpdateRemoteVolume(m_blockvolume.RemoteFilename, RemoteVolumeState.Uploading, -1, null, m_transaction);
                                    m_blockvolume.Close();
                                    UpdateIndexVolume();

                                    using(new Logging.Timer("CommitUpdateRemoteVolume"))
                                        m_transaction.Commit();
                                    m_transaction = m_database.BeginTransaction();

                                    m_backend.Put(m_blockvolume, m_indexvolume);

                                    using(new Logging.Timer("CommitUpdateRemoteVolume"))
                                        m_transaction.Commit();
                                    m_transaction = m_database.BeginTransaction();

                                    m_blockvolume = null;
                                    m_indexvolume = null;
                                }
                            }
                            else
                            {
                                m_database.RemoveRemoteVolume(m_blockvolume.RemoteFilename, m_transaction);
                                if (m_indexvolume != null)
                                    m_database.RemoveRemoteVolume(m_indexvolume.RemoteFilename, m_transaction);
                            }
                        }

                        using(new Logging.Timer("UpdateChangeStatistics"))
                            m_database.UpdateChangeStatistics(m_result);
                        using(new Logging.Timer("VerifyConsistency"))
                            m_database.VerifyConsistency(m_transaction, m_options.Blocksize, m_options.BlockhashSize);

                        var changeCount =
                            m_result.AddedFiles + m_result.ModifiedFiles + m_result.DeletedFiles +
                            m_result.AddedFolders + m_result.ModifiedFolders + m_result.DeletedFolders +
                            m_result.AddedSymlinks + m_result.ModifiedSymlinks + m_result.DeletedSymlinks;

                        //Changes in the filelist triggers a filelist upload
                        if (m_options.UploadUnchangedBackups || changeCount > 0)
                        {
                            using(new Logging.Timer("Uploading a new fileset"))
                            {
                                if (!string.IsNullOrEmpty(m_options.ControlFiles))
                                    foreach(var p in m_options.ControlFiles.Split(new char[] { System.IO.Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries))
                                        m_filesetvolume.AddControlFile(p, m_options.GetCompressionHintFromFilename(p));

                                m_database.WriteFileset(m_filesetvolume, m_transaction);
                                m_filesetvolume.Close();

                                if (m_options.Dryrun)
                                    m_result.AddDryrunMessage(string.Format("Would upload fileset volume: {0}, size: {1}", m_filesetvolume.RemoteFilename, Library.Utility.Utility.FormatSizeString(new FileInfo(m_filesetvolume.LocalFilename).Length)));
                                else
                                {
                                    m_database.UpdateRemoteVolume(m_filesetvolume.RemoteFilename, RemoteVolumeState.Uploading, -1, null, m_transaction);

                                    using(new Logging.Timer("CommitUpdateRemoteVolume"))
                                        m_transaction.Commit();
                                    m_transaction = m_database.BeginTransaction();

                                    m_backend.Put(m_filesetvolume);

                                    using(new Logging.Timer("CommitUpdateRemoteVolume"))
                                        m_transaction.Commit();
                                    m_transaction = m_database.BeginTransaction();

                                }
                            }
                        }
                        else
                        {
                            m_result.AddVerboseMessage("removing temp files, as no data needs to be uploaded");
                            m_database.RemoveRemoteVolume(m_filesetvolume.RemoteFilename, m_transaction);
                        }

                        m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_WaitForUpload);
                        using(new Logging.Timer("Async backend wait"))
                            m_backend.WaitForComplete(m_database, m_transaction);

                        if (m_result.TaskControlRendevouz() != TaskControlState.Stop)
                        {
                            if (m_options.KeepTime.Ticks > 0 || m_options.KeepVersions != 0)
                            {
                                m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_Delete);
                                m_result.DeleteResults = new DeleteResults(m_result);
                                using(var db = new LocalDeleteDatabase(m_database))
                                    new DeleteHandler(m_backend.BackendUrl, m_options, (DeleteResults)m_result.DeleteResults).DoRun(db, m_transaction, true, lastVolumeSize <= m_options.SmallFileSize);

                            }
                            else if (lastVolumeSize <= m_options.SmallFileSize && !m_options.NoAutoCompact)
                            {
                                m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_Compact);
                                m_result.CompactResults = new CompactResults(m_result);
                                using(var db = new LocalDeleteDatabase(m_database))
                                    new CompactHandler(m_backend.BackendUrl, m_options, (CompactResults)m_result.CompactResults).DoCompact(db, true, m_transaction);
                            }
                        }

                        if (m_options.UploadVerificationFile)
                        {
                            m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_VerificationUpload);
                            FilelistProcessor.UploadVerificationFile(m_backend.BackendUrl, m_options, m_result.BackendWriter, m_database, m_transaction);
                        }

                        if (m_options.Dryrun)
                        {
                            m_transaction.Rollback();
                            m_transaction = null;
                        }
                        else
                        {
                            using(new Logging.Timer("CommitFinalizingBackup"))
                                m_transaction.Commit();

                            m_transaction = null;
                            m_database.Vacuum();

                            if (m_result.TaskControlRendevouz() != TaskControlState.Stop && !m_options.NoBackendverification)
                            {
                                m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_PostBackupVerify);
                                using(var backend = new BackendManager(m_backendurl, m_options, m_result.BackendWriter, m_database))
                                {
                                    using(new Logging.Timer("AfterBackupVerify"))
                                        FilelistProcessor.VerifyRemoteList(backend, m_options, m_database, m_result.BackendWriter);
                                    backend.WaitForComplete(m_database, null);
                                }

                                if (m_options.BackupTestSampleCount > 0 && m_database.GetRemoteVolumes().Count() > 0)
                                {
                                    m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_PostBackupTest);
                                    m_result.TestResults = new TestResults(m_result);

                                    using(var testdb = new LocalTestDatabase(m_database))
                                    using(var backend = new BackendManager(m_backendurl, m_options, m_result.BackendWriter, testdb))
                                        new TestHandler(m_backendurl, m_options, new TestResults(m_result))
                                            .DoRun(m_options.BackupTestSampleCount, testdb, backend);
                                }
                            }

                        }

                        m_result.OperationProgressUpdater.UpdatePhase(OperationPhase.Backup_Complete);
                        m_database.WriteResults();
                        m_database.PurgeLogData(m_options.LogRetention);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    m_result.AddError("Fatal error", ex);
                    throw;
                }
                finally
                {
                    if (parallelScanner != null && parallelScanner.IsAlive)
                    {
                        parallelScanner.Abort();
                        parallelScanner.Join(500);
                        if (parallelScanner.IsAlive)
                            m_result.AddWarning("Failed to terminate filecounter thread", null);
                    }

                    if (m_snapshot != null)
                        try { m_snapshot.Dispose(); }
                        catch (Exception ex) { m_result.AddError(string.Format("Failed to dispose snapshot"), ex); }
                        finally { m_snapshot = null; }

                    if (m_transaction != null)
                        try { m_transaction.Rollback(); }
                        catch (Exception ex) { m_result.AddError(string.Format("Rollback error: {0}", ex.Message), ex); }
                }
            }
        }
Beispiel #39
0
 static FSDirectory()
 {
     try
     {
         DIGESTER = Cryptography.HashAlgorithm;
     }
     catch (System.Exception e)
     {
         throw new System.SystemException(e.ToString(), e);
     }
 }
        static FSDirectory()
        {
            {
                try
                {
                    System.String name = SupportClass.AppSettings.Get("Lucene.Net.FSDirectory.class", typeof(FSDirectory).FullName);
                    IMPL = System.Type.GetType(name);
                }
                catch (System.Security.SecurityException)
                {
                    try
                    {
                        IMPL = System.Type.GetType(typeof(FSDirectory).FullName);
                    }
                    catch (System.Exception e)
                    {
                        throw new System.SystemException("cannot load default FSDirectory class: " + e.ToString(), e);
                    }
                }
                catch (System.Exception e)
                {
                    throw new System.SystemException("cannot load FSDirectory class: " + e.ToString(), e);
                }
            }
            {
                try
                {
                    DIGESTER = SupportClass.Cryptography.GetHashAlgorithm();

                }
                catch (System.Exception e)
                {
                    throw new System.SystemException(e.ToString(), e);
                }
            }
        }
        /// <summary>
        /// Adds a chunck of data to checksum list
        /// </summary>
        /// <param name="buffer">The data to add a checksum entry for</param>
        /// <param name="index">The index in the buffer to start reading from</param>
        /// <param name="count">The number of bytes to extract from the array</param>
        public void AddChunk(byte[] buffer, int index, int count)
        {
            if (!m_hashAlgorithm.CanReuseTransform)
                m_hashAlgorithm = Mono.Security.Cryptography.MD4.Create("MD4");

            m_outstream.Write(RDiffBinary.FixEndian(BitConverter.GetBytes(Adler32Checksum.Calculate(buffer, index, count))), 0, 4);
            m_outstream.Write(m_hashAlgorithm.ComputeHash(buffer, index, count), 0, m_stronglen);
        }
        /// <summary>
        /// Constructs a new CheckSum file
        /// <param name="blocklength">The length of a single block</param>
        /// <param name="stronglength">The number of bytes in the MD4 checksum</param>
        /// <param name="outputstream">The stream into which the checksum data is written</param>
        /// </summary>
        public ChecksumFileWriter(System.IO.Stream outputstream, int blocklength, int stronglength)
        {
            if (outputstream == null)
                throw new ArgumentNullException("outputstream");

            m_blocklen = blocklength;
            m_stronglen = stronglength;
            m_outstream = outputstream;
            m_hashAlgorithm = MD4Helper.Create();

            m_hashAlgorithm.Initialize();

            m_outstream.Write(RDiffBinary.SIGNATURE_MAGIC, 0, RDiffBinary.SIGNATURE_MAGIC.Length);
            m_outstream.Write(RDiffBinary.FixEndian(BitConverter.GetBytes(m_blocklen)), 0, 4);
            m_outstream.Write(RDiffBinary.FixEndian(BitConverter.GetBytes(m_stronglen)), 0, 4);
        }