TransformBlock() public method

public TransformBlock ( byte inputBuffer, int inputOffset, int inputCount, byte outputBuffer, int outputOffset ) : int
inputBuffer byte
inputOffset int
inputCount int
outputBuffer byte
outputOffset int
return int
Beispiel #1
0
 public void ComputeHash(HashAlgorithm hash)
 {
     byte[] tmp = Encoding.UTF8.GetBytes (_name);
     hash.TransformBlock (tmp, 0, tmp.Length, null, 0);
     tmp = Encoding.UTF8.GetBytes (_body);
     hash.TransformBlock (tmp, 0, tmp.Length, null, 0);
 }
 /// <summary>Calculates the hash for a Leaf node.</summary>
 /// <param name="data">The data to hash.</param>
 /// <param name="offset">Where in the data array to start hashing.</param>
 /// <param name="count">How many bytes in the data array to hash.</param>
 /// <returns>The resulting Leaf hash.</returns>
 protected byte[] LeafHash(byte[] data, int offset, int count)
 {
     hashAlgorithm.Initialize();
     hashAlgorithm.TransformBlock(new byte[1] {
         0
     }, 0, 1, null, 0);
     hashAlgorithm.TransformFinalBlock(data, offset, count);
     return(hashAlgorithm.Hash);
 }
 public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc)
 {
     UTF8Encoding encoding = new UTF8Encoding(false);
     byte[] bytes = encoding.GetBytes(" " + this.Name + "=\"");
     hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
     bytes = encoding.GetBytes(System.Security.Cryptography.Xml.Utils.EscapeAttributeValue(this.Value));
     hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
     bytes = encoding.GetBytes("\"");
     hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
 }
Beispiel #4
0
 protected int StartTests(HashAlgorithm hash, byte[] input, byte[] result)
 {
     try {
         byte[] ch = hash.ComputeHash(input, 0, input.Length);
         if (!ArrayEquals(ch, result))
             AddError("HB-ST1");
     } catch {
         AddError("HB-ST2");
     }
     try {
         // feed input byte-by-byte
         for(int i = 0; i < input.Length - 1; i++) {
             hash.TransformBlock(input, i, 1, input, i);
         }
         if (input.Length > 0)
             hash.TransformFinalBlock(input, input.Length - 1, 1);
         else
             hash.TransformFinalBlock(input, 0, 0);
         if (!ArrayEquals(hash.Hash, result)) {
             AddError("HB-ST3");
             Console.WriteLine(Encoding.ASCII.GetString(input));
         }
     } catch {
         AddError("HB-ST4");
     } finally {
         hash.Initialize();
     }
     return 4;
 }
        /// <summary>Generates and returns a mask from the specified random seed of the specified length.</summary>
        /// <param name="rgbSeed">The random seed to use for computing the mask. </param>
        /// <param name="cbReturn">The length of the generated mask in bytes. </param>
        /// <returns>A randomly generated mask whose length is equal to the <paramref name="cbReturn" /> parameter.</returns>
        // Token: 0x06002244 RID: 8772 RVA: 0x000790F8 File Offset: 0x000772F8
        public override byte[] GenerateMask(byte[] rgbSeed, int cbReturn)
        {
            HashAlgorithm hashAlgorithm = (HashAlgorithm)CryptoConfig.CreateFromName(this.HashNameValue);

            byte[] inputBuffer = new byte[4];
            byte[] array       = new byte[cbReturn];
            uint   num         = 0U;

            for (int i = 0; i < array.Length; i += hashAlgorithm.Hash.Length)
            {
                Utils.ConvertIntToByteArray(num++, ref inputBuffer);
                hashAlgorithm.TransformBlock(rgbSeed, 0, rgbSeed.Length, rgbSeed, 0);
                hashAlgorithm.TransformFinalBlock(inputBuffer, 0, 4);
                byte[] hash = hashAlgorithm.Hash;
                hashAlgorithm.Initialize();
                if (array.Length - i > hash.Length)
                {
                    Buffer.BlockCopy(hash, 0, array, i, hash.Length);
                }
                else
                {
                    Buffer.BlockCopy(hash, 0, array, i, array.Length - i);
                }
            }
            return(array);
        }
        /// <summary>用指定长度的指定随机种子生成并返回掩码。</summary>
        /// <returns>长度等于 <paramref name="cbReturn" /> 参数的随机生成的掩码。</returns>
        /// <param name="rgbSeed">用于计算掩码的随机种子。</param>
        /// <param name="cbReturn">生成的掩码的长度(以字节为单位)。</param>
        public override byte[] GenerateMask(byte[] rgbSeed, int cbReturn)
        {
            HashAlgorithm hashAlgorithm = (HashAlgorithm)CryptoConfig.CreateFromName(this.HashNameValue);

            byte[] counter   = new byte[4];
            byte[] numArray  = new byte[cbReturn];
            uint   num       = 0;
            int    dstOffset = 0;

            while (dstOffset < numArray.Length)
            {
                Utils.ConvertIntToByteArray(num++, ref counter);
                hashAlgorithm.TransformBlock(rgbSeed, 0, rgbSeed.Length, rgbSeed, 0);
                hashAlgorithm.TransformFinalBlock(counter, 0, 4);
                byte[] hash = hashAlgorithm.Hash;
                hashAlgorithm.Initialize();
                if (numArray.Length - dstOffset > hash.Length)
                {
                    Buffer.BlockCopy((Array)hash, 0, (Array)numArray, dstOffset, hash.Length);
                }
                else
                {
                    Buffer.BlockCopy((Array)hash, 0, (Array)numArray, dstOffset, numArray.Length - dstOffset);
                }
                dstOffset += hashAlgorithm.Hash.Length;
            }
            return(numArray);
        }
Beispiel #7
0
        public override byte[] GenerateMask(byte[] rgbSeed, int cbReturn)
        {
            using (HashAlgorithm hasher = CryptoConfig.CreateFromName(_hashNameValue) as HashAlgorithm)
            {
                if (hasher is null)
                {
                    throw new CryptographicException(SR.Format(SR.Cryptography_UnknownHashAlgorithm, _hashNameValue));
                }

                byte[] rgbCounter = new byte[4];
                byte[] rgbT       = new byte[cbReturn];

                uint counter = 0;
                for (int ib = 0; ib < rgbT.Length;)
                {
                    //  Increment counter -- up to 2^32 * sizeof(Hash)
                    Helpers.ConvertIntToByteArray(counter++, rgbCounter);
                    hasher.TransformBlock(rgbSeed, 0, rgbSeed.Length, rgbSeed, 0);
                    hasher.TransformFinalBlock(rgbCounter, 0, 4);
                    byte[] hash = hasher.Hash;
                    hasher.Initialize();
                    Buffer.BlockCopy(hash, 0, rgbT, ib, Math.Min(rgbT.Length - ib, hash.Length));

                    ib += hasher.Hash.Length;
                }

                return(rgbT);
            }
        }
Beispiel #8
0
        public static string Hash(Stream input, HashAlgorithm algorithm)
        {
            System.Security.Cryptography.HashAlgorithm hasher = GetAlgorithm(algorithm);
            byte[] buffer = new byte[StreamBufferSize];
            int    read;
            long   currentPosition = 0L;
            long   streamLength    = input.Length;

            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                currentPosition += read;
#pragma warning disable IDE0045 // Convert to conditional expression
                if (currentPosition < streamLength)
                {
                    _ = hasher.TransformBlock(buffer, 0, read, buffer, 0);
                }
                else
                {
                    _ = hasher.TransformFinalBlock(buffer, 0, read);
                }
#pragma warning restore IDE0045 // Convert to conditional expression
            }
            byte[] hashBytes = hasher.Hash;
            string hastStr   = hashBytes.ToHex();
            return(hastStr);
        }
        public override byte[] GenerateMask(byte[] rgbSeed, int cbReturn)
        {
            HashAlgorithm algorithm = (HashAlgorithm)CryptoConfig.CreateFromName(this.HashNameValue);

            byte[] counter = new byte[4];
            byte[] dst     = new byte[cbReturn];
            uint   num     = 0;

            for (int i = 0; i < dst.Length; i += algorithm.Hash.Length)
            {
                Utils.ConvertIntToByteArray(num++, ref counter);
                algorithm.TransformBlock(rgbSeed, 0, rgbSeed.Length, rgbSeed, 0);
                algorithm.TransformFinalBlock(counter, 0, 4);
                byte[] hash = algorithm.Hash;
                algorithm.Initialize();
                if ((dst.Length - i) > hash.Length)
                {
                    Buffer.BlockCopy(hash, 0, dst, i, hash.Length);
                }
                else
                {
                    Buffer.BlockCopy(hash, 0, dst, i, dst.Length - i);
                }
            }
            return(dst);
        }
 public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc)
 {
     if (this.IsInNodeSet)
     {
         byte[] bytes = new UTF8Encoding(false).GetBytes(System.Security.Cryptography.Xml.Utils.EscapeTextData(this.Value));
         hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
     }
 }
Beispiel #11
0
 protected override byte[] HashFinal()
 {
     if (m_hashing == false)
     {
         m_hash1.TransformBlock(m_inner, 0, m_inner.Length, m_inner, 0);
         m_hashing = true;
     }
     // finalize the original hash
     m_hash1.TransformFinalBlock(EmptyArray <Byte> .Value, 0, 0);
     byte[] hashValue1 = m_hash1.HashValue;
     // write the outer array
     m_hash2.TransformBlock(m_outer, 0, m_outer.Length, m_outer, 0);
     // write the inner hash and finalize the hash
     m_hash2.TransformBlock(hashValue1, 0, hashValue1.Length, hashValue1, 0);
     m_hashing = false;
     m_hash2.TransformFinalBlock(EmptyArray <Byte> .Value, 0, 0);
     return(m_hash2.HashValue);
 }
Beispiel #12
0
 public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc)
 {
     if (IsInNodeSet)
     {
         UTF8Encoding utf8 = new UTF8Encoding(false);
         byte[] rgbData = utf8.GetBytes(Utils.EscapeTextData(Value));
         hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
     }
 }
Beispiel #13
0
        private byte[] ComputeBaseValue()
        {
            _hash.Initialize();
            _hash.TransformBlock(_password, 0, _password.Length, _password, 0);
            if (_salt != null)
            {
                _hash.TransformBlock(_salt, 0, _salt.Length, _salt, 0);
            }
            _hash.TransformFinalBlock(EmptyArray <Byte> .Value, 0, 0);
            _baseValue = _hash.Hash;
            _hash.Initialize();

            for (int i = 1; i < (_iterations - 1); i++)
            {
                _hash.ComputeHash(_baseValue);
                _baseValue = _hash.Hash;
            }
            return(_baseValue);
        }
Beispiel #14
0
 private static void AddFileToHash(string filename, HashAlgorithm hashService, StreamFilter filter = null, Encoding encoding = null)
 {
     if (filter == null || filter == StreamFilter.None)
     {
         using (var stream = File.OpenRead(filename))
         {
             var buffer = new byte[1200000];
             var bytesRead = stream.Read(buffer, 0, buffer.Length);
             while (bytesRead > 1)
             {
                 hashService.TransformBlock(buffer, 0, bytesRead, buffer, 0);
                 bytesRead = stream.Read(buffer, 0, buffer.Length);
             }
         }
     }
     else
     {
         if (encoding == null)
         {
             if (Path.GetExtension(filename).Equals(".res", StringComparison.InvariantCultureIgnoreCase))
             {
                 encoding = Encoding.Unicode;
             }
             else
             {
                 encoding = Encoding.Default;
             }
         }
         using (var stream = File.OpenRead(filename))
         {
             using (var reader = new StreamReader(stream, encoding))
             {
                 foreach (var line in filter.ReadAllLines(reader))
                 {
                     var lineBuffer = encoding.GetBytes(line);
                     hashService.TransformBlock(lineBuffer, 0, lineBuffer.Length, lineBuffer, 0);
                 }
             }
         }
     }
 }
Beispiel #15
0
 public void FIPS186_e(string testName, HashAlgorithm hash, byte[] input, byte[] result)
 {
     byte[] copy = new byte [input.Length];
     for (int i=0; i < input.Length - 1; i++)
         hash.TransformBlock (input, i, 1, copy, i);
     hash.TransformFinalBlock (input, input.Length - 1, 1);
     // LAMESPEC or FIXME: TransformFinalBlock doesn't return HashValue !
     // AssertEquals (testName + ".e.1", result, output);
     Assert.AreEqual (result, hash.Hash, testName + ".e");
     // required or next operation will still return old hash
     hash.Initialize ();
 }
 public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc)
 {
     if (this.IsInNodeSet)
     {
         byte[] bytes;
         UTF8Encoding encoding = new UTF8Encoding(false);
         if (docPos == DocPosition.AfterRootElement)
         {
             bytes = encoding.GetBytes("(char) 10");
             hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
         }
         bytes = encoding.GetBytes("<?");
         hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
         bytes = encoding.GetBytes(this.Name);
         hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
         if ((this.Value != null) && (this.Value.Length > 0))
         {
             bytes = encoding.GetBytes(" " + this.Value);
             hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
         }
         bytes = encoding.GetBytes("?>");
         hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
         if (docPos == DocPosition.BeforeRootElement)
         {
             bytes = encoding.GetBytes("(char) 10");
             hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
         }
     }
 }
        public HashTransformer(StateHash hash)
        {
            mHash = hash;
            if (hash == null)
                return;

            mHasher = new SHA256Cng();

            var bytes = mHash.GetBytes();
            mHasher.TransformBlock(bytes, 0, bytes.Length, null, 0);

            mCryptoStream = new CryptoStream(new FakeStream(), mHasher, CryptoStreamMode.Write);
        }
        /// <summary>
        /// Prepares to resume.
        /// </summary>
        /// <param name="successfulLength">Successful length.</param>
        /// <param name="successfulPart">Successful part.</param>
        /// <param name="hashAlg">Hash algorithm</param>
        public static void PrepareResume(long successfulLength, Stream successfulPart, HashAlgorithm hashAlg) {
            byte[] buffer = new byte[4096];
            int pos = 0;
            while (pos < successfulLength) {
                int l = successfulPart.Read(buffer, 0, (int)Math.Min(buffer.Length, successfulLength - pos));
                if (l <= 0) {
                    throw new IOException(string.Format("File stream is shorter ({0}) than the given length {1}", pos, successfulLength));
                }

                hashAlg.TransformBlock(buffer, 0, l, buffer, 0);
                pos += l;
            }
        }
 public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc)
 {
     if (this.IsInNodeSet && this.IncludeComments)
     {
         UTF8Encoding encoding = new UTF8Encoding(false);
         byte[] bytes = encoding.GetBytes("(char) 10");
         if (docPos == DocPosition.AfterRootElement)
         {
             hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
         }
         bytes = encoding.GetBytes("<!--");
         hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
         bytes = encoding.GetBytes(this.Value);
         hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
         bytes = encoding.GetBytes("-->");
         hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
         if (docPos == DocPosition.BeforeRootElement)
         {
             bytes = encoding.GetBytes("(char) 10");
             hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
         }
     }
 }
Beispiel #20
0
        //----------------------------------------------------------------------------------

        protected override byte[] HashFinal()
        {
            if (!_bhashing)
            {
                _h1.TransformBlock(_binner, 0, _blocksize, _binner, 0);
                _bhashing = true;
            }

            _h1.TransformFinalBlock(new byte[0], 0, 0);
            _h2.TransformBlock(_bouter, 0, _blocksize, _bouter, 0);
            _h2.TransformFinalBlock(_h1.Hash, 0, _h1.Hash.Length);
            _bhashing = false;

            return(_h2.Hash);
        }
Beispiel #21
0
 public byte[] ComputeHash(FileStream fileStream, HashAlgorithm hashAlgorithm, byte[] buffer)
 {
     while (true)
     {
         int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
         if (bytesRead == buffer.Length)
         {
             hashAlgorithm.TransformBlock(buffer, 0, bytesRead, buffer, 0);
         }
         else
         {
             hashAlgorithm.TransformFinalBlock(buffer, 0, bytesRead);
             return hashAlgorithm.Hash;
         }
     }
 }
Beispiel #22
0
        /// <summary>
        /// Computes a file hash without loading the entire file into memory.
        /// </summary>
        /// <param name="filePath">Path of the file to hash.</param>
        /// <param name="hashAlgorithm">Algorithm to hash in.  Example: 'new SHA1CryptoServiceProvider()'</param>
        /// <returns></returns>
        public static string ComputeHash(string filePath, HashAlgorithm hashAlgorithm)
        {
            try
            {
                using (var stream = (Stream)File.Open(filePath, FileMode.Open))
                {
                    int _bufferSize = 4096; // this makes it impossible to change the buffer size while computing

                    byte[] readAheadBuffer, buffer;
                    int readAheadBytesRead, bytesRead;
                    long size, totalBytesRead = 0;

                    size = stream.Length;
                    readAheadBuffer = new byte[_bufferSize];
                    readAheadBytesRead = stream.Read(readAheadBuffer, 0, readAheadBuffer.Length);

                    totalBytesRead += readAheadBytesRead;

                    do
                    {
                        bytesRead = readAheadBytesRead;
                        buffer = readAheadBuffer;

                        readAheadBuffer = new byte[_bufferSize];
                        readAheadBytesRead = stream.Read(readAheadBuffer, 0, readAheadBuffer.Length);

                        totalBytesRead += readAheadBytesRead;

                        if (readAheadBytesRead == 0)
                            hashAlgorithm.TransformFinalBlock(buffer, 0, bytesRead);
                        else
                            hashAlgorithm.TransformBlock(buffer, 0, bytesRead, buffer, 0);
                    } while (readAheadBytesRead != 0);
                }

                string hex = "";
                foreach (byte b in hashAlgorithm.Hash)
                    hex += b.ToString("x2");

                return hex.ToLower();
            }
            catch (Exception)
            {
                return null;
            }
        }
Beispiel #23
0
        public override void Reset()
        {
            state      = 0;
            position   = 0;
            hashnumber = 0;

            hash = HashAlgorithm.Create(HashNameValue);
            if (SaltValue != null)
            {
                hash.TransformBlock(password, 0, password.Length, password, 0);
                hash.TransformFinalBlock(SaltValue, 0, SaltValue.Length);
                initial = hash.Hash;
            }
            else
            {
                initial = hash.ComputeHash(password);
            }
        }
        /// <summary>Process the last block of data.</summary>
        /// <param name="inputBuffer">The block of data to process.</param>
        /// <param name="inputOffset">Where to start in the block.</param>
        /// <param name="inputCount">How many bytes need to be processed.</param>
        /// <returns>The results of the completed hash calculation.</returns>
        override protected byte[] ProcessFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
        {
            lock (syncLock) {
                if (inputCount > 0)
                {
                    workingNodes.Add(new HashNode(hashAlgorithm.ComputeHash(inputBuffer, inputOffset, inputCount), Count, (Count + inputCount - 1)));
                }
                finalNodes = workingNodes;

                // Calculate the top hash.
                hashAlgorithm.Initialize();
                foreach (HashNode node in this)
                {
                    hashAlgorithm.TransformBlock(node.Hash, 0, node.Hash.Length, null, 0);
                }
                hashAlgorithm.TransformFinalBlock(new byte[1], 0, 0);

                return(hashAlgorithm.Hash);
            }
        }
        /// <exception cref="IOException">The underlying stream is null or closed. </exception>
        /// <exception cref="DirectoryNotFoundException">The specified path is invalid, (for example, it is on an unmapped drive). </exception>
        /// <exception cref="UnauthorizedAccessException"><paramref name="path" /> specified a directory.-or- The caller does not have the required permission. </exception>
        /// <exception cref="FileNotFoundException">The file specified in <paramref name="path" /> was not found. </exception>
        /// <exception cref="CryptographicUnexpectedOperationException"><see cref="F:System.Security.Cryptography.HashAlgorithm.HashValue" /> is null. </exception>
        /// <exception cref="ObjectDisposedException">The object has already been disposed.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="oldValue" /> is null. </exception>
        /// <exception cref="ArgumentException"><paramref name="oldValue" /> is the empty string (""). </exception>
        /// <exception cref="Exception">A delegate callback throws an exception.</exception>
        /// <exception cref="OperationCanceledException">The token has had cancellation requested.</exception>
        public string CalculateHash(string file, HashAlgorithm algorithm, CancellationToken token)
        {
            byte[] buffer;
            byte[] oldBuffer;
            int bytesRead;
            int oldBytesRead;
            long size;
            long totalBytesRead = 0;
            using (var bufferedStream = new BufferedStream(File.OpenRead(file)))
            {
                using (algorithm)
                {
                    size = bufferedStream.Length;
                    buffer = new byte[4096];
                    bytesRead = bufferedStream.Read(buffer, 0, buffer.Length);
                    totalBytesRead += bytesRead;

                    do
                    {
                        token.ThrowIfCancellationRequested();
                        oldBytesRead = bytesRead;
                        oldBuffer = buffer;

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

                        if (bytesRead == 0)
                        {
                            algorithm.TransformFinalBlock(oldBuffer, 0, oldBytesRead);
                        }
                        else
                        {
                            algorithm.TransformBlock(oldBuffer, 0, oldBytesRead, oldBuffer, 0);
                        }
                        HashProgressUpdate?.Invoke(this, new ProgressEventArgs((double) totalBytesRead*100/size));
                    } while (bytesRead != 0);
                    return BitConverter.ToString(algorithm.Hash).Replace("-", string.Empty).ToUpper();
                }
            }
        }
        protected override byte[] HashFinal()
        {
            if (_disposed)
            {
                throw new ObjectDisposedException("HMAC");
            }
            State = 0;

            Block.Final();
            byte[] intermediate = _algo.Hash;

            byte[] buf = KeySetup(Key, 0x5C);
            _algo.Initialize();
            _algo.TransformBlock(buf, 0, buf.Length, buf, 0);
            _algo.TransformFinalBlock(intermediate, 0, intermediate.Length);
            byte[] hash = _algo.Hash;
            _algo.Initialize();
            // zeroize sensitive data
            Array.Clear(buf, 0, buf.Length);
            Array.Clear(intermediate, 0, intermediate.Length);
            return(hash);
        }
Beispiel #27
0
        public override void Reset()
        {
#if NET_2_0
            state = 0;
#else
            // note: Reset doesn't change state
#endif
            position   = 0;
            hashnumber = 0;

            hash = HashAlgorithm.Create(HashNameValue);
            if (SaltValue != null)
            {
                hash.TransformBlock(password, 0, password.Length, password, 0);
                hash.TransformFinalBlock(SaltValue, 0, SaltValue.Length);
                initial = hash.Hash;
            }
            else
            {
                initial = hash.ComputeHash(password);
            }
        }
        public override byte[] GenerateMask(byte[] rgbSeed, int cbReturn)
        {
            using (HashAlgorithm hasher = SHA1.Create())
            {
                byte[] rgbCounter = new byte[4];
                byte[] rgbT       = new byte[cbReturn];

                uint counter = 0;
                for (int ib = 0; ib < rgbT.Length;)
                {
                    //  Increment counter -- up to 2^32 * sizeof(Hash)
                    Helpers.ConvertIntToByteArray(counter++, rgbCounter);
                    hasher.TransformBlock(rgbSeed, 0, rgbSeed.Length, rgbSeed, 0);
                    hasher.TransformFinalBlock(rgbCounter, 0, 4);
                    byte[] hash = hasher.Hash;
                    hasher.Initialize();
                    Buffer.BlockCopy(hash, 0, rgbT, ib, Math.Min(rgbT.Length - ib, hash.Length));

                    ib += hasher.Hash.Length;
                }
                return(rgbT);
            }
        }
Beispiel #29
0
        public static bool TestMultiBlock(HashAlgorithm hash, byte[] data, byte[] digest)
        {
            int pos = 0;

            hash.Initialize();

            while (data.Length - pos >= 1)
                pos += hash.TransformBlock(data, pos, 1, data, pos);

            hash.TransformFinalBlock(data, pos, data.Length - pos);

            if (!CompareBytes(hash.Hash, digest))
            {
                Log.Comment("MultiBlock test failed");
                return false;
            }

            return true;
        }
 private void HashString(HashAlgorithm hasher, string hashThis)
 {
     var bytes = Encoding.UTF8.GetBytes(hashThis);
     hasher.TransformBlock(bytes, 0, bytes.Length, null, 0);
 }
 /// <summary>
 /// Calculates an ongoing hash.
 /// </summary>
 /// <param name="input">The data to calculate the hash on.</param>
 /// <param name="offset">The offset in the input buffer to calculate from.</param>
 /// <param name="count">The number of bytes to use from input.</param>
 /// <param name="hash">The hash algorithm to use.</param>
 internal static void ComputeHash(byte[] input, int offset, int count, HashAlgorithm hash)
 {
     hash.TransformBlock(input, offset, count, null, 0);
 }
Beispiel #32
0
	public override void Reset () 
	{
		state = 0;
		position = 0;
		hashnumber = 0;

		hash = HashAlgorithm.Create (HashNameValue);
		if (SaltValue != null) {
			hash.TransformBlock (password, 0, password.Length, password, 0);
			hash.TransformFinalBlock (SaltValue, 0, SaltValue.Length);
			initial = hash.Hash;
		}
		else
			initial = hash.ComputeHash (password);
	}
Beispiel #33
0
 private static void ComputeMore(HashAlgorithm hasher, int data)
 {
     // TODO: make this thread local to save the byte array allocation.
     byte[] bytes = BitConverter.GetBytes(data);
     hasher.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
 }
 private void HashIsHidden(HashAlgorithm hasher, bool isHidden)
 {
     var bytes = new[] {isHidden ? (byte) 1 : (byte) 0};
     hasher.TransformBlock(bytes, 0, bytes.Length, null, 0);
 }
Beispiel #35
0
        public (SM2DeriveBytes?Key, byte[] Verifier, byte[] PeerVerifier) DeriveKey(
            EcPoint peerPubKey, EcPoint peerR, ReadOnlySpan <byte> peerIdent)
        {
            if (!_ephemeralKey.Param.Curve.ValidatePoint(peerPubKey))
            {
                throw new CryptographicException();
            }

            if (!_ephemeralKey.Param.Curve.ValidatePoint(peerR))
            {
                throw new CryptographicException();
            }

            var pkBytes = (_ephemeralKey.Param.Curve.BitLength + 7) / 8;

            var zPeer = SM2.ZValue(_ephemeralKey.Param, _hash, peerIdent, peerPubKey);
            var w     = _ephemeralKey.Param.BitLength;

            if (_ephemeralKey.Param.N.IsPowerOfTwo)
            {
                w -= 1;
            }
            w = (ushort)((w >> 1) + (w & 1) - 1);
            var w2 = (BigInteger)1 << w;
            var x2 = w2 + (_ephemeralKey.Q.X & (w2 - 1));
            var t  = (_privateKey + x2 * _ephemeralKey.D) % _ephemeralKey.Param.N;
            var x1 = w2 + (peerR.X & (w2 - 1));

            var vi = _ephemeralKey.Param.Curve.MultiplyAndAdd(1, peerPubKey, x1, peerR, _rng);
            var v  = _ephemeralKey.Param.Curve.ToAffine(_ephemeralKey.Param.Curve.Multiply(_ephemeralKey.Param.H * t, vi, _rng));

            if (v.Inf)
            {
                return(null, null !, null !);
            }

            var za  = _responder ? zPeer : _zValue;
            var zb  = _responder ? _zValue : zPeer;
            var zl  = za.Length + zb.Length;
            var key = new byte[pkBytes * 2 + zl];
            var xv  = v.X.ToByteArrayUBe(pkBytes);
            var yv  = v.Y.ToByteArrayUBe(pkBytes);

            xv.CopyTo(key, 0);
            yv.CopyTo(key, pkBytes);
            za.CopyTo(key, pkBytes * 2);
            zb.CopyTo(key, pkBytes * 2 + za.Length);

            var kdf = new SM2DeriveBytes(key, _hash);

            var ra = _responder ? peerR : _ephemeralKey.Q;
            var rb = _responder ? _ephemeralKey.Q : peerR;

#if NETSTANDARD2_0 || NETSTANDARD2_1
            _hash.Initialize();
            _hash.TransformBlock(xv, 0, pkBytes, null, 0);
            _hash.TransformBlock(za, 0, za.Length, null, 0);
            _hash.TransformBlock(zb, 0, zb.Length, null, 0);
            _hash.TransformBlock(ra.X.ToByteArrayUBe(pkBytes), 0, pkBytes, null, 0);
            _hash.TransformBlock(ra.Y.ToByteArrayUBe(pkBytes), 0, pkBytes, null, 0);
            _hash.TransformBlock(rb.X.ToByteArrayUBe(pkBytes), 0, pkBytes, null, 0);
            _hash.TransformFinalBlock(rb.Y.ToByteArrayUBe(pkBytes), 0, pkBytes);
            var si = _hash.Hash;

            _hash.Initialize();
            key[0] = 2;
            _hash.TransformBlock(key, 0, 1, null, 0);
            _hash.TransformBlock(yv, 0, pkBytes, null, 0);
            _hash.TransformFinalBlock(si, 0, si.Length);
            var sb = _hash.Hash;

            _hash.Initialize();
            key[0] = 3;
            _hash.TransformBlock(key, 0, 1, null, 0);
            _hash.TransformBlock(yv, 0, pkBytes, null, 0);
            _hash.TransformFinalBlock(si, 0, si.Length);
            var sa = _hash.Hash;
#else
            var sib = ArrayPool <byte> .Shared.Rent(pkBytes * 5 + zl);

            xv.CopyTo(sib, 0);
            za.CopyTo(sib, pkBytes);
            zb.CopyTo(sib, pkBytes + za.Length);
            ra.X.ToByteArrayUBe(pkBytes).CopyTo(sib, zl + pkBytes);
            ra.Y.ToByteArrayUBe(pkBytes).CopyTo(sib, zl + pkBytes * 2);
            rb.X.ToByteArrayUBe(pkBytes).CopyTo(sib, zl + pkBytes * 3);
            rb.Y.ToByteArrayUBe(pkBytes).CopyTo(sib, zl + pkBytes * 4);
            var si = _hash.ComputeHash(sib, 0, pkBytes * 5 + zl);
            ArrayPool <byte> .Shared.Return(sib);

            var sbb = ArrayPool <byte> .Shared.Rent(pkBytes + si.Length + 1);

            yv.CopyTo(sbb, 1);
            si.CopyTo(sbb, pkBytes + 1);
            sbb[0] = 2;
            var sb = _hash.ComputeHash(sbb, 0, pkBytes + si.Length + 1);

            sbb[0] = 3;
            var sa = _hash.ComputeHash(sbb, 0, pkBytes + si.Length + 1);
            ArrayPool <byte> .Shared.Return(sbb);
#endif

            return(kdf, _responder ? sb : sa, _responder ? sa : sb);
        }
Beispiel #36
0
	public override void Reset () 
	{
#if NET_2_0
		state = 0;
#else
		// note: Reset doesn't change state
#endif
		position = 0;
		hashnumber = 0;

		hash = HashAlgorithm.Create (HashNameValue);
		if (SaltValue != null) {
			hash.TransformBlock (password, 0, password.Length, password, 0);
			hash.TransformFinalBlock (SaltValue, 0, SaltValue.Length);
			initial = hash.Hash;
		}
		else
			initial = hash.ComputeHash (password);
	}
        private int DownloadNextChunk(IDocument remoteDocument, long offset, long remainingBytes, Transmission transmission, Stream outputstream, HashAlgorithm hashAlg) {
            lock(this.disposeLock) {
                if (this.disposed) {
                    transmission.Status = TransmissionStatus.ABORTED;
                    throw new ObjectDisposedException(transmission.Path);
                }

                IContentStream contentStream = remoteDocument.GetContentStream(remoteDocument.ContentStreamId, offset, remainingBytes);
                transmission.Length = remoteDocument.ContentStreamLength;
                transmission.Position = offset;

                using (var remoteStream = contentStream.Stream)
                using (var forwardstream = new ForwardReadingStream(remoteStream))
                using (var offsetstream = new OffsetStream(forwardstream, offset))
                using (var progress = transmission.CreateStream(offsetstream)) {
                    byte[] buffer = new byte[8 * 1024];
                    int result = 0;
                    int len;
                    while ((len = progress.Read(buffer, 0, buffer.Length)) > 0) {
                        outputstream.Write(buffer, 0, len);
                        hashAlg.TransformBlock(buffer, 0, len, buffer, 0);
                        result += len;
                        outputstream.Flush();
                    }

                    return result;
                }
            }
        }
Beispiel #38
0
        private static void ComputeMore(
            HashAlgorithm hasher, byte[] code, int startIndex, Instruction instruction)
        {
            if (instruction == null)
                throw new ArgumentNullException("instruction");

            // Find the opcode part.
            // TODO: in X86Codec, since a fixable location always comes after
            // prefix+opcode+modrm+sib, we should put the fixable location as
            // a property of the instruction instead of the operand.
            int opcodeLength = instruction.EncodedLength;
            foreach (Operand operand in instruction.Operands)
            {
                if (operand.FixableLocation.Length > 0)
                    opcodeLength = Math.Min(opcodeLength, operand.FixableLocation.StartOffset);
            }

            // Since the opcode uniquely determines the displacement and
            // immediate format, we only need to hash the opcode part and
            // don't need to hash dummy zeros for the remaining part of the
            // instruction.
            hasher.TransformBlock(code, startIndex, opcodeLength, code, startIndex);
        }
 private void HashDateTime(HashAlgorithm hasher, DateTime dateTime)
 {
     var bytes = BitConverter.GetBytes(dateTime.ToBinary());
     hasher.TransformBlock(bytes, 0, bytes.Length, null, 0);
 }
Beispiel #40
0
        /// <summary>
        /// Compute a hash of the bytes of the buffer within the frames of the given NetMQMessage.
        /// </summary>
        /// <param name="hash">the hashing-algorithm to employ</param>
        /// <param name="message">the NetMQMessage whose frames are to be hashed</param>
        private void Hash(HashAlgorithm hash, NetMQMessage message)
        {
            foreach (var frame in message)
            {
                // Access the byte-array that is the frame's buffer.
                byte[] bytes = frame.ToByteArray(true);

                // Compute the hash value for the region of the input byte-array (bytes), starting at index 0,
                // and copy the resulting hash value back into the same byte-array.
                hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
            }
        }
Beispiel #41
0
        private void Hash(HashAlgorithm hash, NetMQMessage message)
        {
            foreach (NetMQFrame frame in message)
              {
            byte[] bytes = frame.ToByteArray(true);

            hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
              }
        }
Beispiel #42
0
 void AddToDigest(HashAlgorithm algorithm, byte[] buffer, int offset, int count)
 {
     algorithm.TransformBlock(buffer, offset, count, buffer, offset);
 }
        /// <summary>
        /// Downloads the file and returns the SHA-1 hash of the content of the saved file
        /// </summary>
        /// <param name="remoteDocument">Remote document.</param>
        /// <param name="localFileStream">Local taget file stream.</param>
        /// <param name="transmission">Transmission status.</param>
        /// <param name="hashAlg">Hash algoritm, which should be used to calculate hash of the uploaded stream content</param>
        /// <exception cref="IOException">On any disc or network io exception</exception>
        /// <exception cref="DisposeException">If the remote object has been disposed before the dowload is finished</exception>
        /// <exception cref="AbortException">If download is aborted</exception>
        /// <exception cref="CmisException">On exceptions thrown by the CMIS Server/Client</exception>
        public void DownloadFile(
            IDocument remoteDocument,
            Stream localFileStream,
            Transmission transmission,
            HashAlgorithm hashAlg,
            UpdateChecksum update = null)
        {
            byte[] buffer = new byte[8 * 1024];
            int len;

            if (localFileStream.Length > 0) {
                localFileStream.Seek(0, SeekOrigin.Begin);
                while ((len = localFileStream.Read(buffer, 0, buffer.Length)) > 0) {
                    hashAlg.TransformBlock(buffer, 0, len, buffer, 0);
                }
            }

            long offset = localFileStream.Position;
            long? fileLength = remoteDocument.ContentStreamLength;
            if (fileLength <= offset) {
                transmission.Length = fileLength.GetValueOrDefault();
                transmission.Position = offset;
                hashAlg.TransformFinalBlock(new byte[0], 0, 0);
                return;
            }

            DotCMIS.Data.IContentStream contentStream = null;
            if (offset > 0) {
                long remainingBytes = (long)fileLength - offset;
                transmission.Length = remoteDocument.ContentStreamLength;
                transmission.Position = offset;
                contentStream = remoteDocument.GetContentStream(remoteDocument.ContentStreamId, offset, remainingBytes);
            } else {
                contentStream = remoteDocument.GetContentStream();
            }

            using (var transmissionStream = transmission.CreateStream(localFileStream))
            using (CryptoStream hashstream = new CryptoStream(transmissionStream, hashAlg, CryptoStreamMode.Write))
            using (Stream remoteStream = contentStream != null ? contentStream.Stream : new MemoryStream(0)) {
                transmission.Length = remoteDocument.ContentStreamLength;
                transmission.Position = offset;
                int written = 0;
                while ((len = remoteStream.Read(buffer, 0, buffer.Length)) > 0) {
                    lock (this.disposeLock) {
                        if (this.disposed) {
                            transmission.Status = TransmissionStatus.ABORTED;
                            throw new ObjectDisposedException(transmission.Path);
                        }

                        try {
                            hashstream.Write(buffer, 0, len);
                            hashstream.Flush();
                            written += len;
                        } catch (Exception) {
                            this.UpdateHash(hashAlg, localFileStream.Length, update);
                            throw;
                        }

                        if (written >= 1024 * 1024) {
                            this.UpdateHash(hashAlg, localFileStream.Length, update);
                            written = 0;
                        }
                    }
                }

                if (written > 0) {
                    this.UpdateHash(hashAlg, localFileStream.Length, update);
                }
            }
        }
Beispiel #44
0
		internal byte[] GetHash (HashAlgorithm hash)
		{
			if (blockNo < 1)
				ReadFirstBlock ();
			fs.Position = blockLength;

			// hash the rest of the file
			long n;
			int addsize = 0;
			// minus any authenticode signature (with 8 bytes header)
			if (dirSecurityOffset > 0) {
				// it is also possible that the signature block 
				// starts within the block in memory (small EXE)
				if (dirSecurityOffset < blockLength) {
					blockLength = dirSecurityOffset;
					n = 0;
				} else {
					n = dirSecurityOffset - blockLength;
				}
			} else if (coffSymbolTableOffset > 0) {
				fileblock[PEOffset + 12] = 0;
				fileblock[PEOffset + 13] = 0;
				fileblock[PEOffset + 14] = 0;
				fileblock[PEOffset + 15] = 0;
				fileblock[PEOffset + 16] = 0;
				fileblock[PEOffset + 17] = 0;
				fileblock[PEOffset + 18] = 0;
				fileblock[PEOffset + 19] = 0;
				// it is also possible that the signature block 
				// starts within the block in memory (small EXE)
				if (coffSymbolTableOffset < blockLength) {
					blockLength = coffSymbolTableOffset;
					n = 0;
				} else {
					n = coffSymbolTableOffset - blockLength;
				}
			} else {
				addsize = (int) (fs.Length & 7);
				if (addsize > 0)
					addsize = 8 - addsize;
				
				n = fs.Length - blockLength;
			}

			// Authenticode(r) gymnastics
			// Hash from (generally) 0 to 215 (216 bytes)
			int pe = peOffset + 88;
			hash.TransformBlock (fileblock, 0, pe, fileblock, 0);
			// then skip 4 for checksum
			pe += 4;
			// Continue hashing from (generally) 220 to 279 (60 bytes)
			hash.TransformBlock (fileblock, pe, 60, fileblock, pe);
			// then skip 8 bytes for IMAGE_DIRECTORY_ENTRY_SECURITY
			pe += 68;

			// everything is present so start the hashing
			if (n == 0) {
				// hash the (only) block
				hash.TransformFinalBlock (fileblock, pe, blockLength - pe);
			}
			else {
				// hash the last part of the first (already in memory) block
				hash.TransformBlock (fileblock, pe, blockLength - pe, fileblock, pe);

				// hash by blocks of 4096 bytes
				long blocks = (n >> 12);
				int remainder = (int)(n - (blocks << 12));
				if (remainder == 0) {
					blocks--;
					remainder = 4096;
				}
				// blocks
				while (blocks-- > 0) {
					fs.Read (fileblock, 0, fileblock.Length);
					hash.TransformBlock (fileblock, 0, fileblock.Length, fileblock, 0);
				}
				// remainder
				if (fs.Read (fileblock, 0, remainder) != remainder)
					return null;

				if (addsize > 0) {
					hash.TransformBlock (fileblock, 0, remainder, fileblock, 0);
					hash.TransformFinalBlock (new byte [addsize], 0, addsize);
				} else {
					hash.TransformFinalBlock (fileblock, 0, remainder);
				}
			}
			return hash.Hash;
		}
        /// <summary>
        /// Downloads the file and returns the SHA-1 hash of the content of the saved file
        /// </summary>
        /// <param name="remoteDocument">Remote document.</param>
        /// <param name="localFileStream">Local taget file stream.</param>
        /// <param name="transmission">Transmission status.</param>
        /// <param name="hashAlg">Hash algoritm, which should be used to calculate hash of the uploaded stream content</param>
        /// <param name="update">Not or not yet used</param>
        /// <exception cref="IOException">On any disc or network io exception</exception>
        /// <exception cref="DisposeException">If the remote object has been disposed before the dowload is finished</exception>
        /// <exception cref="AbortException">If download is aborted</exception>
        /// <exception cref="CmisException">On exceptions thrown by the CMIS Server/Client</exception>
        public void DownloadFile(
            IDocument remoteDocument,
            Stream localFileStream,
            Transmission transmission,
            HashAlgorithm hashAlg,
            UpdateChecksum update = null)
        {
            {
                byte[] buffer = new byte[8 * 1024];
                int len;
                while ((len = localFileStream.Read(buffer, 0, buffer.Length)) > 0) {
                    hashAlg.TransformBlock(buffer, 0, len, buffer, 0);
                }
            }

            long? fileLength = remoteDocument.ContentStreamLength;

            // Download content if exists
            if (fileLength > 0) {
                long offset = localFileStream.Position;
                long remainingBytes = (fileLength != null) ? (long)fileLength - offset : this.ChunkSize;
                try {
                    do {
                        offset += this.DownloadNextChunk(remoteDocument, offset, remainingBytes, transmission, localFileStream, hashAlg);
                    } while(fileLength == null);
                } catch (DotCMIS.Exceptions.CmisConstraintException) {
                }
            } else {
                transmission.Position = 0;
                transmission.Length = 0;
            }

            hashAlg.TransformFinalBlock(new byte[0], 0, 0);
        }