Initialize() public abstract method

public abstract Initialize ( ) : void
return void
示例#1
0
 /// <summary>Initializes the list.</summary>
 override public void Initialize()
 {
     lock (syncLock) {
         base.Initialize();
         hashAlgorithm.Initialize();
         workingNodes = new List <HashTreeNode>();
     }
 }
        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);
        }
示例#3
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>用指定长度的指定随机种子生成并返回掩码。</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);
        }
        /// <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);
        }
示例#6
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);
            }
        }
 internal byte[] GetDigestedBytes(HashAlgorithm hash)
 {
     this.m_c14nDoc.WriteHash(hash, DocPosition.BeforeRootElement, this.m_ancMgr);
     hash.TransformFinalBlock(new byte[0], 0, 0);
     byte[] buffer = (byte[]) hash.Hash.Clone();
     hash.Initialize();
     return buffer;
 }
示例#8
0
 public void FIPS186_b(string testName, HashAlgorithm hash, byte[] input, byte[] result)
 {
     byte[] output = hash.ComputeHash (input, 0, input.Length);
     Assert.AreEqual (result, output, testName + ".b.1");
     Assert.AreEqual (result, hash.Hash, testName + ".b.2");
     // required or next operation will still return old hash
     hash.Initialize ();
 }
示例#9
0
 public void FIPS186_d(string testName, HashAlgorithm hash, byte[] input, byte[] result)
 {
     hash.TransformFinalBlock (input, 0, input.Length);
     // LAMESPEC or FIXME: TransformFinalBlock doesn't return HashValue !
     // AssertEquals( testName + ".d.1", result, output );
     Assert.AreEqual (result, hash.Hash, testName + ".d");
     // required or next operation will still return old hash
     hash.Initialize ();
 }
示例#10
0
 public void FIPS186_c(string testName, HashAlgorithm hash, byte[] input, byte[] result)
 {
     MemoryStream ms = new MemoryStream (input);
     byte[] output = hash.ComputeHash (ms);
     Assert.AreEqual (result, output, testName + ".c.1");
     Assert.AreEqual (result, hash.Hash, testName + ".c.2");
     // required or next operation will still return old hash
     hash.Initialize ();
 }
示例#11
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);
        }
示例#12
0
		/// <summary>
		/// Computes the Sha1 hash value for the specified byte array.
		/// </summary>
		/// <param name="input">The byte-array to compute the hash value for.</param>
		/// <returns>The computed hash value.</returns>
		public static byte[] ComputeSha1Hash(byte[] input)
		{
			byte[] hash = null;
			using (HashAlgorithm sha1 = new HashAlgorithm(HashAlgorithmType.SHA1))
			{
				sha1.Initialize();
				hash = sha1.ComputeHash(input);
			}
			return hash;
		}
示例#13
0
        // Generate a mask using a specific set and byte count.
        //
        // This implementation is based on the description in PKCS #1 v2.1.
        // ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1.pdf
        public override byte[] GenerateMask(byte[] rgbSeed, int cbReturn)
        {
            // Validate the parameters.
            if (rgbSeed == null)
            {
                throw new ArgumentNullException("rgbSeed");
            }
            else if (cbReturn < 0)
            {
                throw new ArgumentOutOfRangeException
                          ("cbReturn", _("ArgRange_NonNegative"));
            }

            // Create the final mask buffer.
            byte[] mask = new byte [cbReturn];

            // Create the hash algorithm instance.
            HashAlgorithm alg = HashAlgorithm.Create(hashName);

            // Create the mask.
            byte[] numbuf = new byte [4];
            byte[] hash;
            int    hashSize = alg.HashSize;
            int    count    = 0;
            int    index    = 0;

            while (index < cbReturn)
            {
                numbuf[0] = (byte)(count >> 24);
                numbuf[1] = (byte)(count >> 16);
                numbuf[2] = (byte)(count >> 8);
                numbuf[3] = (byte)count;
                alg.InternalHashCore(rgbSeed, 0, rgbSeed.Length);
                alg.InternalHashCore(numbuf, 0, 4);
                hash = alg.InternalHashFinal();
                if (hashSize <= (cbReturn - index))
                {
                    Array.Copy(hash, 0, mask, index, hashSize);
                }
                else
                {
                    Array.Copy(hash, 0, mask, index, cbReturn - index);
                }
                Array.Clear(hash, 0, hash.Length);
                alg.Initialize();
                ++count;
                index += hashSize;
            }
            Array.Clear(numbuf, 0, numbuf.Length);

            // The mask has been generated.
            return(null);
        }
        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);
        }
示例#15
0
 /// <summary>
 /// Initialize a new checksum object.
 /// </summary>
 /// <param name="alg">The checksumming algorithm to use.</param>
 public Checksum(Algorithm alg)
 {
     switch (alg)
     {
         case Algorithm.SHA0:
             hash = new SHA0();
             break;
         case Algorithm.SHA1:
             hash = HashAlgorithm.Create("SHA1");
             break;
         case Algorithm.MD5:
             hash = HashAlgorithm.Create("MD5");
             break;
     }
     hash.Initialize();
     this.alg = alg;
 }
示例#16
0
        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);
            }
        }
示例#17
0
        public static bool TestComputeHash(HashAlgorithm hash, byte[] data, byte[] digest)
        {
            hash.Initialize();

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

            return true;
        }
        // tests a hash algorithm instance 
        public static bool TestHash(HashAlgorithm hash)
        {
            bool bRes = true;
            // decide on the number of passes
            int nPasses = m_Rnd.Next(MAX_PASSES) + 1;
            Log.Comment("Doing " + nPasses + " passes...");

            while (0 != nPasses--)
            {
                // init the hash object
                hash.Initialize();

                // create a random data blob
                int nSize = m_Rnd.Next(MAX_SIZE);
                byte[] abBlob = new byte[nSize];
                Log.Comment("Test buffer size is " + nSize);

                // first try ComputeHash
                byte[] hash1 = hash.ComputeHash(abBlob);

                //			Log.Comment("Hash1:");
                //			PrintByteArray(hash1);

                // now try stream
                hash.Initialize();

                byte[] hash2 = hash.TransformFinalBlock(abBlob, 0, abBlob.Length);

                //CryptoStream cs = new CryptoStream(CryptoStream.Null, hash, CryptoStreamMode.Write);
                //cs.Write(abBlob, 0, abBlob.Length);
                //cs.Close();
                //byte[] hash2 = hash.Hash;

                //			Log.Comment("Hash2:");
                //			PrintByteArray(hash2);

                if (Compare(hash1, hash2))
                {
                    Log.Comment(" OK.");
                }
                else
                {
                    bRes = false;
                    Log.Comment(" FAILED. Hashes are different.");
                }

            }
            return bRes;
        }
示例#19
0
 public MyRSA()
 {
     m_hasher = MySHA256.Create();
     m_hasher.Initialize();
 }
示例#20
0
        byte[] Crypt(byte[] key, byte[] salt, int rounds, HashAlgorithm A)
        {
            byte[] P = null, S = null, H = null, I = null;

            try
            {
                A.Initialize();
                AddToDigest(A, key);
                AddToDigest(A, salt);
                AddToDigest(A, key);
                FinishDigest(A);

                I = (byte[])A.Hash.Clone();

                A.Initialize();
                AddToDigest(A, key);
                AddToDigest(A, salt);

                AddToDigestRolling(A, I, 0, I.Length, key.Length);

                int length = key.Length;
                for (int i = 0; i < 31 && length != 0; i++)
                {
                    AddToDigest(A, (length & (1 << i)) != 0 ? I : key);
                    length &= ~(1 << i);
                }
                FinishDigest(A);

                H = (byte[])A.Hash.Clone();

                A.Initialize();
                for (int i = 0; i < key.Length; i++)
                {
                    AddToDigest(A, key);
                }
                FinishDigest(A);

                P = new byte[key.Length];
                CopyRolling(A.Hash, 0, A.Hash.Length, P);

                A.Initialize();
                for (int i = 0; i < 16 + H[0]; i++)
                {
                    AddToDigest(A, salt);
                }
                FinishDigest(A);

                S = new byte[salt.Length];
                CopyRolling(A.Hash, 0, A.Hash.Length, S);

                for (int i = 0; i < rounds; i++)
                {
                    A.Initialize();
                    if ((i & 1) != 0) { AddToDigest(A, P); }
                    if ((i & 1) == 0) { AddToDigest(A, H); }
                    if ((i % 3) != 0) { AddToDigest(A, S); }
                    if ((i % 7) != 0) { AddToDigest(A, P); }
                    if ((i & 1) != 0) { AddToDigest(A, H); }
                    if ((i & 1) == 0) { AddToDigest(A, P); }
                    FinishDigest(A);

                    Array.Copy(A.Hash, H, H.Length);
                }

                byte[] crypt = new byte[H.Length];
                int[] permutation = GetCryptPermutation();
                for (int i = 0; i < crypt.Length; i++)
                {
                    crypt[i] = H[permutation[i]];
                }

                return crypt;
            }
            finally
            {
                A.Clear();
                Security.Clear(P);
                Security.Clear(S);
                Security.Clear(H);
                Security.Clear(I);
            }
        }
示例#21
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);
        }
示例#22
0
        byte[] Crypt(byte[] key, byte[] salt, int rounds, HashAlgorithm A)
        {
            byte[] H = null;

            try
            {
                A.Initialize();
                AddToDigest(A, salt);
                AddToDigest(A, key);
                FinishDigest(A);

                H = (byte[])A.Hash.Clone();

                for (int i = 0; i < (1 << rounds); i++)
                {
                    A.Initialize();
                    AddToDigest(A, H);
                    AddToDigest(A, key);
                    FinishDigest(A);

                    Array.Copy(A.Hash, H, H.Length);
                }

                return (byte[])H.Clone();
            }
            finally
            {
                A.Clear();
                Security.Clear(H);
            }
        }
示例#23
0
        static string SaltedCrypt(HashAlgorithm algorithm, byte[] password, byte[] salt)
        {
            // If we're under the hash length, assume we only have the salt.
            int hashLength = algorithm.HashSize / 8;
            int saltOffset = salt.Length < hashLength ? 0 : hashLength;
            int saltLength = salt.Length - saltOffset;

            byte[] saltedHash = new byte[hashLength + saltLength];
            try
            {
                algorithm.Initialize();
                algorithm.TransformBlock(password, 0, password.Length, password, 0);
                algorithm.TransformBlock(salt, saltOffset, saltLength, salt, saltOffset);
                algorithm.TransformFinalBlock(new byte[0], 0, 0);

                Array.Copy(algorithm.Hash, saltedHash, hashLength);
                Array.Copy(salt, saltOffset, saltedHash, hashLength, saltLength);
                string crypt = Convert.ToBase64String(saltedHash);
                return crypt;
            }
            finally
            {
                algorithm.Clear();
                Security.Clear(saltedHash);
            }
        }
示例#24
0
        public static bool TestSingleBlock(HashAlgorithm hash, byte[] data, byte[] digest)
        {
            hash.Initialize();
            hash.TransformFinalBlock(data, 0, data.Length);

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

            return true;
        }
示例#25
0
 public Hashing(HashAlgorithm hashAlgorithm)
 {
     _hashAlgorithm = hashAlgorithm;
     _hashAlgorithm.Initialize();
 }
示例#26
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 ();
 }
        private static byte[] HashStream(HashAlgorithm hashAlgorithm, Stream s)
        {
            s.Seek(0, SeekOrigin.Begin);

            // reset algorithm
            hashAlgorithm.Initialize();
            return hashAlgorithm.ComputeHash(s);
        }
示例#28
0
		public HashWriter(): base(CultureInfo.InvariantCulture) {
			hash = SHA1.Create();
			hash.Initialize();
		}
		//private bool VerifySignature (ASN1 cs, byte[] calculatedMessageDigest, string hashName) 
		private bool VerifySignature (PKCS7.SignedData sd, byte[] calculatedMessageDigest, HashAlgorithm ha) 
		{
			string contentType = null;
			ASN1 messageDigest = null;
//			string spcStatementType = null;
//			string spcSpOpusInfo = null;

			for (int i=0; i < sd.SignerInfo.AuthenticatedAttributes.Count; i++) {
				ASN1 attr = (ASN1) sd.SignerInfo.AuthenticatedAttributes [i];
				string oid = ASN1Convert.ToOid (attr[0]);
				switch (oid) {
					case "1.2.840.113549.1.9.3":
						// contentType
						contentType = ASN1Convert.ToOid (attr[1][0]);
						break;
					case "1.2.840.113549.1.9.4":
						// messageDigest
						messageDigest = attr[1][0];
						break;
					case "1.3.6.1.4.1.311.2.1.11":
						// spcStatementType (Microsoft code signing)
						// possible values
						// - individualCodeSigning (1 3 6 1 4 1 311 2 1 21)
						// - commercialCodeSigning (1 3 6 1 4 1 311 2 1 22)
//						spcStatementType = ASN1Convert.ToOid (attr[1][0][0]);
						break;
					case "1.3.6.1.4.1.311.2.1.12":
						// spcSpOpusInfo (Microsoft code signing)
/*						try {
							spcSpOpusInfo = System.Text.Encoding.UTF8.GetString (attr[1][0][0][0].Value);
						}
						catch (NullReferenceException) {
							spcSpOpusInfo = null;
						}*/
						break;
					default:
						break;
				}
			}
			if (contentType != spcIndirectDataContext)
				return false;

			// verify message digest
			if (messageDigest == null)
				return false;
			if (!messageDigest.CompareValue (calculatedMessageDigest))
				return false;

			// verify signature
			string hashOID = CryptoConfig.MapNameToOID (ha.ToString ());
			
			// change to SET OF (not [0]) as per PKCS #7 1.5
			ASN1 aa = new ASN1 (0x31);
			foreach (ASN1 a in sd.SignerInfo.AuthenticatedAttributes)
				aa.Add (a);
			ha.Initialize ();
			byte[] p7hash = ha.ComputeHash (aa.GetBytes ());

			byte[] signature = sd.SignerInfo.Signature;
			// we need to find the specified certificate
			string issuer = sd.SignerInfo.IssuerName;
			byte[] serial = sd.SignerInfo.SerialNumber;
			foreach (X509Certificate x509 in coll) {
				if (CompareIssuerSerial (issuer, serial, x509)) {
					// don't verify is key size don't match
					if (x509.PublicKey.Length > (signature.Length >> 3)) {
						RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) x509.RSA;
						if (rsa.VerifyHash (p7hash, hashOID, signature)) {
							signerChain.LoadCertificates (coll);
							trustedRoot = signerChain.Build (x509);
							signingCertificate = x509;
							break; 
						}
					}
				}
			}

			for (int i=0; i < sd.SignerInfo.UnauthenticatedAttributes.Count; i++) {
				ASN1 attr = (ASN1) sd.SignerInfo.UnauthenticatedAttributes [i];
				string oid = ASN1Convert.ToOid (attr [0]);
				switch (oid) {
					case PKCS7.Oid.countersignature:
						// SEQUENCE {
						//   OBJECT IDENTIFIER
						//     countersignature (1 2 840 113549 1 9 6)
						//   SET {
						PKCS7.SignerInfo cs = new PKCS7.SignerInfo (attr [1]);
						trustedTimestampRoot = VerifyCounterSignature (cs, signature);
						break;
					default:
						// we don't support other unauthenticated attributes
						break;
				}
			}

			return (trustedRoot && trustedTimestampRoot);
		}
示例#30
0
        // Get the pseudo-random key bytes.
        public override byte[] GetBytes(int cb)
        {
            // Initialize the pseudo-random generator.
            if (hashAlgorithm == null)
            {
                if (strHashName == null)
                {
                    strHashName = "MD5";
                }
                hashAlgorithm = HashAlgorithm.Create(strHashName);
                blockNum      = 1;
                size          = hashAlgorithm.HashSize;
                posn          = size;
            }

            // Allocate the result array and then fill it.
            byte[] result = new byte [cb];
            int    index  = 0;
            int    templen;

            while (cb > 0)
            {
                // Copy existing data from the previous block.
                if (posn < size)
                {
                    templen = (size - posn);
                    if (cb < templen)
                    {
                        templen = cb;
                    }
                    Array.Copy(block, posn, result, index, templen);
                    cb    -= templen;
                    index -= templen;
                    posn   = size;
                    if (cb <= 0)
                    {
                        break;
                    }
                }

                // Generate a new block using the hash algorithm.
                if (strPassword != null)
                {
                    byte[] pwd = Encoding.UTF8.GetBytes(strPassword);
                    hashAlgorithm.InternalHashCore(pwd, 0, pwd.Length);
                    Array.Clear(pwd, 0, pwd.Length);
                }
                if (rgbSalt != null)
                {
                    hashAlgorithm.InternalHashCore
                        (rgbSalt, 0, rgbSalt.Length);
                }
                byte[] numbuf = new byte [4];
                numbuf[0] = (byte)(blockNum >> 24);
                numbuf[1] = (byte)(blockNum >> 16);
                numbuf[2] = (byte)(blockNum >> 8);
                numbuf[3] = (byte)blockNum;
                hashAlgorithm.InternalHashCore(numbuf, 0, 4);
                Array.Clear(numbuf, 0, numbuf.Length);
                byte[] lastHash = hashAlgorithm.InternalHashFinal();
                hashAlgorithm.Initialize();
                templen = iterations;
                byte[] temphash;
                while (templen > 1)
                {
                    hashAlgorithm.InternalHashCore
                        (lastHash, 0, lastHash.Length);
                    temphash = hashAlgorithm.InternalHashFinal();
                    hashAlgorithm.Initialize();
                    for (int tempindex = 0; tempindex < lastHash.Length;
                         ++tempindex)
                    {
                        lastHash[tempindex] ^= temphash[tempindex];
                    }
                    Array.Clear(temphash, 0, temphash.Length);
                    --templen;
                }
                if (block != null)
                {
                    Array.Clear(block, 0, block.Length);
                }
                block = lastHash;
                ++blockNum;
                posn = 0;
            }

            // Return the result array to the caller.
            return(result);
        }
示例#31
0
        byte[] Crypt(byte[] key, byte[] salt, byte[] prefix, HashAlgorithm A)
        {
            byte[] H = null, I = null;

            try
            {
                A.Initialize();
                AddToDigest(A, key);
                AddToDigest(A, salt);
                AddToDigest(A, key);
                FinishDigest(A);

                I = (byte[])A.Hash.Clone();

                A.Initialize();
                AddToDigest(A, key);
                AddToDigest(A, prefix);
                AddToDigest(A, salt);

                AddToDigestRolling(A, I, 0, I.Length, key.Length);

                int length = key.Length;
                for (int i = 0; i < 31 && length != 0; i++)
                {
                    AddToDigest(A, new[] { (length & (1 << i)) != 0 ? (byte)0 : key[0] });
                    length &= ~(1 << i);
                }
                FinishDigest(A);

                H = (byte[])A.Hash.Clone();

                for (int i = 0; i < 1000; i++)
                {
                    A.Initialize();
                    if ((i & 1) != 0) { AddToDigest(A, key); }
                    if ((i & 1) == 0) { AddToDigest(A, H); }
                    if ((i % 3) != 0) { AddToDigest(A, salt); }
                    if ((i % 7) != 0) { AddToDigest(A, key); }
                    if ((i & 1) != 0) { AddToDigest(A, H); }
                    if ((i & 1) == 0) { AddToDigest(A, key); }
                    FinishDigest(A);

                    Array.Copy(A.Hash, H, H.Length);
                }

                byte[] crypt = new byte[H.Length];
                int[] permutation = new[] { 11, 4, 10, 5, 3, 9, 15, 2, 8, 14, 1, 7, 13, 0, 6, 12 };
                Array.Reverse(permutation);
                for (int i = 0; i < crypt.Length; i++)
                {
                    crypt[i] = H[permutation[i]];
                }

                return crypt;
            }
            finally
            {
                A.Clear();
                Security.Clear(H);
                Security.Clear(I);
            }
        }
示例#32
0
文件: HMACGEN.cs 项目: jar0l/crypto
        //----------------------------------------------------------------------------------

        public override void Initialize()
        {
            _h1.Initialize();
            _h2.Initialize();
            _bhashing = false;
        }
示例#33
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;
        }
示例#34
0
	// Generate the hash value for this assembly using a given algorith.
	public byte[] GenerateHash(HashAlgorithm hashAlg)
			{
				if(hashAlg == null)
				{
					throw new ArgumentNullException("hashAlg");
				}
				byte[] rawData = RawData;
				if(rawData == null)
				{
					return null;
				}
				hashAlg.Initialize();
				return hashAlg.ComputeHash(rawData);
			}
示例#35
0
文件: HMAC.cs 项目: alisci01/cs2cpp
 public override void Initialize()
 {
     m_hash1.Initialize();
     m_hash2.Initialize();
     m_hashing = false;
 }
示例#36
0
        public static bool CompareHashes(HashAlgorithm algorithm1, HashAlgorithm algorithm2, byte[] data)
        {
            algorithm1.Initialize();
            algorithm2.Initialize();

            byte[] hash1 = algorithm1.ComputeHash(data);
            byte[] hash2 = algorithm2.ComputeHash(data);

            if (!CompareBytes(hash1, hash2))
            {
                Log.Comment("ERROR - HASH VALUE MISCOMPARISON!\n");
                Log.Comment("Algorithm 1 : " + algorithm1.ToString());
                Log.Comment("Algorithm 2 : " + algorithm2.ToString());
                Log.Comment("Data: " + ByteArrayToString(data));
                return false;
            }

            return true;
        }
        private byte[] TransformByCryptoStream(HashAlgorithm algorithm, byte[] bytes)
        {
            algorithm.Initialize();

              return TransformByCryptoStream((ICryptoTransform)algorithm, bytes);
        }
示例#38
0
        static string UnsaltedCrypt(HashAlgorithm algorithm, byte[] password)
        {
            try
            {
                algorithm.Initialize();
                algorithm.TransformBlock(password, 0, password.Length, password, 0);
                algorithm.TransformFinalBlock(new byte[0], 0, 0);

                string crypt = Convert.ToBase64String(algorithm.Hash);
                return crypt;
            }
            finally
            {
                algorithm.Clear();
            }
        }