Exemplo n.º 1
0
        public override byte[] Hash(byte[] data, byte[] salt, int version, int iterations = 1000, int outputLength = 64)
        {
            var crypto = new MD5CryptoServiceProvider();
            var output = new byte[outputLength];
            crypto.TransformBlock(data, 0, data.Length, output, 0);

            salt.CopyTo(output, output.Length - salt.Length);
            return output;
        }
 public void CalcHash()
 {
     using (var hash = new MD5CryptoServiceProvider()) {
         foreach (var xt in mXmitTaskList) {
             hash.TransformBlock(xt.xmitData, 0, xt.xmitData.Length, xt.xmitData, 0);
         }
         hash.TransformFinalBlock(new byte[0], 0, 0);
         mXmitDataHash = hash.Hash;
     }
 }
Exemplo n.º 3
0
        internal static byte[] EncodePapPassword(byte[] userPassBytes, byte[] requestAuthenticator, string sharedSecret)
        {
            if (userPassBytes.Length > 128)
            {
                throw new InvalidOperationException("the PAP password cannot be greater than 128 bytes...");
            }

            byte[] encryptedPass = null;
            if (userPassBytes.Length % 16 == 0)
            {
                encryptedPass = new byte[userPassBytes.Length];
            }
            else
            {
                encryptedPass = new byte[((userPassBytes.Length / 16) * 16) + 16];
            }
            Array.Copy(userPassBytes, 0, encryptedPass, 0, userPassBytes.Length);
            for (int i = userPassBytes.Length; i < encryptedPass.Length; i++)
            {
                encryptedPass[i] = 0;
            }

            byte[] sharedSecretBytes = System.Text.Encoding.ASCII.GetBytes(sharedSecret);

            System.Security.Cryptography.MD5 md5;
            for (int chunk = 0; chunk < (encryptedPass.Length / 16); chunk++)
            {
                md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                md5.TransformBlock(sharedSecretBytes, 0, sharedSecretBytes.Length, sharedSecretBytes, 0);
                if (chunk == 0)
                {
                    md5.TransformFinalBlock(requestAuthenticator, 0, requestAuthenticator.Length);
                }
                else
                {
                    md5.TransformFinalBlock(encryptedPass, (chunk - 1) * 16, 16);
                }

                byte[] hash = md5.Hash;

                for (int i = 0; i < 16; i++)
                {
                    int j = i + chunk * 16;
                    encryptedPass[j] = (byte)(hash[i] ^ encryptedPass[j]);
                }
            }

            return(encryptedPass);
        }
        public byte[] CalcHash()
        {
            mRecvFragmentList = mRecvFragmentList.OrderBy(o => o.StartPos).ToList();

            using (var hash = new MD5CryptoServiceProvider()) {
                foreach (var f in mRecvFragmentList) {
                    hash.TransformBlock(f.Content, 0, f.Content.Length, f.Content, 0);
                }
                hash.TransformFinalBlock(new byte[0], 0, 0);

                byte[] result = new byte[HASH_BYTES];
                Array.Copy(hash.Hash, result, HASH_BYTES);
                return result;
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// ���ļ�����MD5����
        /// </summary>
        /// <param name="filePath"></param>
        public static void MD5File(string filePath)
        {
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            int bufferSize = 1048576; // ����������1MB
            byte[] buff = new byte[bufferSize];

            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            md5.Initialize();

            long offset = 0;
            while (offset < fs.Length)
            {
                long readSize = bufferSize;
                if (offset + readSize > fs.Length)
                {
                    readSize = fs.Length - offset;
                }

                fs.Read(buff, 0, Convert.ToInt32(readSize)); // ��ȡһ�����ݵ�������

                if (offset + readSize < fs.Length) // �������һ��
                {
                    md5.TransformBlock(buff, 0, Convert.ToInt32(readSize), buff, 0);
                }
                else // ���һ��
                {
                    md5.TransformFinalBlock(buff, 0, Convert.ToInt32(readSize));
                }

                offset += bufferSize;
            }

            fs.Close();
            byte[] result = md5.Hash;
            md5.Clear();

            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < result.Length; i++)
            {
                sb.Append(result[i].ToString("X2"));
            }

            Console.WriteLine(sb.ToString());
            Console.ReadLine();
        }
Exemplo n.º 6
0
        /// <summary>
        /// MD5 hashing of the file using blocks, use 7Mb for chunks
        /// </summary>
        /// <param name="FileName">the file</param>
        /// <param name="blocksize">the chunk size</param>
        /// <returns></returns>
        public static string MD5HashFile(string FileName, int blocksize)
        {
            byte[] result;
            byte[] chunk = new byte[blocksize];
            string HashString;

            System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            try
            {
                System.IO.Stream stream = System.IO.File.OpenRead(FileName);

                long filesize = stream.Length;
                while (filesize - stream.Position > chunk.Length)
                {
                    stream.Read(chunk, 0, blocksize);
                    md5.TransformBlock(chunk, 0, blocksize, chunk, 0);

                    OnHashProgressed(new HashEventArgs(FileName, (int)(100 * stream.Position / filesize), stream.Position, filesize));
                }
                int readCount = stream.Read(chunk, 0, (int)(filesize - stream.Position));
                md5.TransformFinalBlock(chunk, 0, readCount);

                result = md5.Hash;

                System.Text.StringBuilder output = new System.Text.StringBuilder(2 + (result.Length * 2));

                foreach (byte b in result)
                {
                    output.Append(b.ToString("x2"));
                }
                HashString = output.ToString().ToUpper();
            }
            catch (Exception ex)
            {
                chunk  = null;
                result = null;
                GC.Collect();
                return("0x0000");
            }
            chunk  = null;
            result = null;
            GC.Collect();
            return(HashString);
        }
Exemplo n.º 7
0
        public static byte[] encodePapPassword(byte[] userPassBytes,byte[] requestAuthenticator,string sharedSecret)
        {
            if (userPassBytes.Length > 128)
            throw new InvalidOperationException("the PAP password cannot be greater than 128 bytes...");

            byte[] encryptedPass = null;
            if (userPassBytes.Length % 16 == 0) {
            encryptedPass = new byte[userPassBytes.Length];
            } else {
            encryptedPass = new byte[((userPassBytes.Length / 16) * 16) + 16];
            }
            System.Array.Copy(userPassBytes, 0, encryptedPass, 0, userPassBytes.Length);
            for(int i = userPassBytes.Length; i < encryptedPass.Length; i++) {
            encryptedPass[i] = 0;
            }

            byte[] sharedSecretBytes = System.Text.Encoding.ASCII.GetBytes(sharedSecret);

            System.Security.Cryptography.MD5 md5;
            for (int chunk = 0; chunk < (encryptedPass.Length / 16); chunk++)
            {
            md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            md5.TransformBlock(sharedSecretBytes, 0, sharedSecretBytes.Length, sharedSecretBytes, 0);
            if (chunk == 0)
                md5.TransformFinalBlock(requestAuthenticator, 0, requestAuthenticator.Length);
            else
                md5.TransformFinalBlock(encryptedPass, (chunk - 1) * 16, 16);

            byte[] hash = md5.Hash;

            for (int i = 0; i < 16; i++){
                int j = i + chunk*16;
                encryptedPass[j] = (byte) (hash[i] ^ encryptedPass[j]);
            }

            }

            return encryptedPass;
        }
Exemplo n.º 8
0
        /// <summary>
        /// 获取文件的MD5值
        /// </summary>
        /// <param name="fileName"> 文件名 </param>
        /// <returns> 32位MD5 </returns>
        public static string GetFileMd5(string fileName)
        {
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            const int bufferSize = 1024 * 1024;
            byte[] buffer = new byte[bufferSize];

            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            md5.Initialize();

            long offset = 0;
            while (offset < fs.Length)
            {
                long readSize = bufferSize;
                if (offset + readSize > fs.Length)
                {
                    readSize = fs.Length - offset;
                }
                fs.Read(buffer, 0, (int)readSize);
                if (offset + readSize < fs.Length)
                {
                    md5.TransformBlock(buffer, 0, (int)readSize, buffer, 0);
                }
                else
                {
                    md5.TransformFinalBlock(buffer, 0, (int)readSize);
                }
                offset += bufferSize;
            }
            fs.Close();
            byte[] result = md5.Hash;
            md5.Clear();
            StringBuilder sb = new StringBuilder(32);
            foreach (byte b in result)
            {
                sb.Append(b.ToString("X2"));
            }
            return sb.ToString();
        }
Exemplo n.º 9
0
    private const int Md5ReadLen = 16 * 1024;       // 一次读取长度 16384 = 16 * kb


    public static string GetMD5HashFromFile(string fileName)
    {
        byte[] buffer = new byte[Md5ReadLen];

        int readLength = 0;//每次读取长度

        var output = new byte[Md5ReadLen];

        using (Stream inputStream = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            using (System.Security.Cryptography.HashAlgorithm hashAlgorithm = new System.Security.Cryptography.MD5CryptoServiceProvider())
            {
                while ((readLength = inputStream.Read(buffer, 0, buffer.Length)) > 0) // 计算MD5
                {
                    hashAlgorithm.TransformBlock(buffer, 0, readLength, output, 0);
                }

                //完成最后计算,必须调用(由于上一部循环已经完成所有运算,所以调用此方法时后面的两个参数都为0)
                hashAlgorithm.TransformFinalBlock(buffer, 0, 0);

                var retVal = hashAlgorithm.Hash;

                var sb = new System.Text.StringBuilder(32);

                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }

                hashAlgorithm.Clear();

                inputStream.Close();

                return(sb.ToString());
            }
        }
    }
Exemplo n.º 10
0
        private void GenerateStaticContent ()
        {
            resources.Clear ();
            var random = new Random ();
            var root = "/tmp/hyena-download-test-server";

            try {
                Directory.Delete (root, true);
            } catch {
            }

            Directory.CreateDirectory (root);

            for (int i = 0; i < ResourceCount; i++) {
                var md5 = new MD5CryptoServiceProvider ();
                var resource = new Resource () {
                    Path = Path.Combine (root, i.ToString ()),
                    Length = random.Next (MinResourceSize, MaxResourceSize + 1)
                };

                if (Debug) Console.WriteLine ();

                using (var stream = File.OpenWrite (resource.Path)) {
                    var buffer = new byte[32 << 10];
                    long written = 0;
                    long remaining;

                    while ((remaining = resource.Length - written) > 0) {
                        var buffer_length = remaining > buffer.Length
                            ? (int)buffer.Length
                            : (int)remaining;

                        random.NextBytes (buffer);
                        stream.Write (buffer, 0, buffer_length);
                        written += buffer_length;
                        md5.TransformBlock (buffer, 0, buffer_length, null, 0);

                        if (Debug) Console.Write ("\rCreating resource: {0} ({1:0.00} MB): [{2}/{3}]  {4:0.0}% ",
                            resource.Path, resource.Length / 1024.0 / 1024.0,
                            i + 1, ResourceCount,
                            written / (double)resource.Length * 100.0);
                    }
                    
                    md5.TransformFinalBlock (buffer, 0, 0);
                    resource.Checksum = BitConverter.ToString (md5.Hash).Replace ("-", String.Empty).ToLower ();
                }

                resources.Add (resource);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// 生成某个文件的MD5
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private string GenMD5(string fileName)
        {
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            int bufferSize = 1048576; // 缓冲区大小,1MB
            byte[] buff = new byte[bufferSize];

            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            md5.Initialize();

            long offset = 0;
            while (offset < fs.Length)
            {
                long readSize = bufferSize;
                if (offset + readSize > fs.Length)
                {
                    readSize = fs.Length - offset;
                }

                fs.Read(buff, 0, Convert.ToInt32(readSize)); // 读取一段数据到缓冲区

                if (offset + readSize < fs.Length) // 不是最后一块
                {
                    md5.TransformBlock(buff, 0, Convert.ToInt32(readSize), buff, 0);
                }
                else // 最后一块
                {
                    md5.TransformFinalBlock(buff, 0, Convert.ToInt32(readSize));
                }

                offset += bufferSize;
            }

            fs.Close();
            byte[] result = md5.Hash;
            md5.Clear();

            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < result.Length; i++)
            {
                sb.Append(result[i].ToString("X2"));
            }
            return sb.ToString();
        }
Exemplo n.º 12
0
 protected static byte[] ComputeMD5(byte[] key, byte[] salt, int saltHashRounds = DefaultSaltHashRounds)
 {
     // TODO: Test that saltHashRounds >= 1
     using (var md5 = new MD5CryptoServiceProvider())
     {
         // Hash key
         md5.TransformBlock(key, 0, key.Length, null, 0);
         // Hash salt (saltHashRounds-1) times
         for(int i = 1; i < saltHashRounds; i++)
         {
             md5.TransformBlock(salt, 0, salt.Length, null, 0);
         }
         // Final salt hash iteration
         md5.TransformFinalBlock(salt, 0, salt.Length);
         return md5.Hash;
     }
 }
        void HashTimer()
        {
            byte[] inArray1 = new byte[24];
            byte[] inArray2 = new byte[30000*sizeof(double)];
            int i;

            for (i = 0; i < 24; i++)
                inArray1[i] = (byte)(23 + i*2);

            MemoryStream binStream = new MemoryStream(inArray2);
            BinaryWriter binWriter = new BinaryWriter(binStream);
            for (i = 0; i < 30000; i++)
                binWriter.Write(i * (double)2.2);

            DateTime timerStart = DateTime.Now;
            for (i = 0; i < nIter; i++)
            {
                MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
                md5Hasher.TransformBlock(inArray1, 0, inArray1.Length, inArray1, 0);
                md5Hasher.TransformFinalBlock(inArray2, 0, inArray2.Length);
                byte[] hash1 = md5Hasher.Hash;
            }
            DateTime timerEnd = DateTime.Now;
            TimeSpan timerDiff = timerEnd - timerStart;
            TimeLabelBlob.Content = String.Format("ChkSum --- Iterations: {0};  Duration: {1:hh\\:mm\\:ss\\.f}", i, timerDiff);

            i = 3;
        }
Exemplo n.º 14
0
        //RSA authentication
        private void DoRSAChallengeResponse()
        {
            //read key
            SSH1UserAuthKey key = new SSH1UserAuthKey(_param.IdentityFile, _param.Password);
            Transmit(
                new SSH1Packet(SSH1PacketType.SSH_CMSG_AUTH_RSA)
                    .WriteBigInteger(key.PublicModulus)
            );
            TraceTransmissionEvent(SSH1PacketType.SSH_CMSG_AUTH_RSA, "RSA challenge-reponse");

            DataFragment response = ReceivePacket();
            SSH1DataReader reader = new SSH1DataReader(response);
            SSH1PacketType pt = (SSH1PacketType) reader.ReadByte();
            if (pt == SSH1PacketType.SSH_SMSG_FAILURE)
                throw new SSHException(Strings.GetString("ServerRefusedRSA"));
            else if (pt != SSH1PacketType.SSH_SMSG_AUTH_RSA_CHALLENGE)
                throw new SSHException(String.Format(Strings.GetString("UnexpectedResponse"), pt));
            TraceReceptionEvent(SSH1PacketType.SSH_SMSG_AUTH_RSA_CHALLENGE, "received challenge");

            //creating challenge
            BigInteger challenge = key.decryptChallenge(reader.ReadMPInt());
            byte[] rawchallenge = RSAUtil.StripPKCS1Pad(challenge, 2).GetBytes();

            //building response
            byte[] hash;
            using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider()) {
                md5.TransformBlock(rawchallenge, 0, rawchallenge.Length, rawchallenge, 0);
                md5.TransformFinalBlock(_sessionID, 0, _sessionID.Length);
                hash = md5.Hash;
            }
            Transmit(
                new SSH1Packet(SSH1PacketType.SSH_CMSG_AUTH_RSA_RESPONSE)
                    .Write(hash)
            );
            TraceReceptionEvent(SSH1PacketType.SSH_CMSG_AUTH_RSA_RESPONSE, "received response");
        }
Exemplo n.º 15
0
        /// <summary>
        /// SSH1 RSA challenge
        /// </summary>
        /// <param name="e">public exponent</param>
        /// <param name="n">public modulus</param>
        /// <param name="encryptedChallenge">encrypted challenge</param>
        /// <param name="sessionId">session id</param>
        /// <param name="responseType">response type</param>
        private void SSH1IRSAChallenge(BigInteger e, BigInteger n, BigInteger encryptedChallenge, byte[] sessionId, uint responseType)
        {
            if (responseType != 1) {
                SendFailure();
                return;
            }

            SSH1UserAuthKey key = SSH1FindKey(e, n);
            if (key == null) {
                SendFailure();
                return;
            }

            BigInteger challenge = key.decryptChallenge(encryptedChallenge);
            byte[] rawchallenge = RSAUtil.StripPKCS1Pad(challenge, 2).GetBytes();
            byte[] hash;
            using (var md5 = new MD5CryptoServiceProvider()) {
                md5.TransformBlock(rawchallenge, 0, rawchallenge.Length, rawchallenge, 0);
                md5.TransformFinalBlock(sessionId, 0, sessionId.Length);
                hash = md5.Hash;
            }

            Send(
                new OpenSSHAgentForwardingMessage(OpenSSHAgentForwardingMessageType.SSH_AGENT_RSA_RESPONSE)
                    .Write(hash)
            );
        }
Exemplo n.º 16
0
        /// <summary>
        /// Create the next upload message.
        /// </summary>
        private void CreateUploadMsg(MD5CryptoServiceProvider md5Hasher, out AnpMsg m, out List<UInt64> CompletedArray)
        {
            m = Share.CreateTransferMsg(KAnpType.KANP_CMD_KFS_PHASE_2);
            CompletedArray = new List<UInt64>();

            // Add the number of submessages field. It will be updated later.
            m.AddUInt32(0);

            // Count the number of submessages.
            int nbSub = 0;

            // Loop until the message is full or we run out of files to upload.
            while (m.PayloadSize() < MAX_UPLOAD_SIZE && UploadIndex != FileArray.Length)
            {
                KfsUploadBatchFile ubf = FileArray[UploadIndex];

                // The transfer of the current file was denied by the
                // server during phase 1. Do not attempt to talk about
                // it in phase 2.
                if (ubf.Status == BatchStatus.Error)
                {
                    UploadNextFile();
                    continue;
                }

                // The transfer of the current file has been cancelled. Add an
                // abort submessage and pass to the next file.
                if (ubf.Status == BatchStatus.Cancelled)
                {
                    m.AddUInt32(2);
                    m.AddUInt32(KAnpType.KANP_KFS_SUBMESSAGE_ABORT);
                    nbSub++;
                    UploadNextFile();
                    continue;
                }

                // The current file is closed. Open the file and set the
                // remaining size.
                if (UploadedFile == null)
                {
                    Debug.Assert(ubf.Status == BatchStatus.Queued);
                    ubf.Status = BatchStatus.Started;
                    UploadedFile = new FileStream(ubf.TransferPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                    RemainingSize = UploadedFile.Length;
                    md5Hasher.Initialize();
                }

                // Add a chunk submessage.
                if (RemainingSize > 0)
                {
                    Debug.Assert(ubf.Status == BatchStatus.Started);

                    // Compute the chunk size.
                    UInt32 chunkSize = Math.Max(MIN_UPLOAD_CHUNK_SIZE, MAX_UPLOAD_SIZE - m.PayloadSize());
                    chunkSize = (UInt32)Math.Min((Int64)chunkSize, RemainingSize);
                    RemainingSize -= chunkSize;

                    // Read the chunk.
                    byte[] chunkData = new byte[chunkSize];
                    UploadedFile.Read(chunkData, 0, (Int32)chunkSize);

                    // Update the hash.
                    md5Hasher.TransformBlock(chunkData, 0, (int)chunkSize, chunkData, 0);

                    // Add the chunk submessage.
                    m.AddUInt32(3);
                    m.AddUInt32(KAnpType.KANP_KFS_SUBMESSAGE_CHUNK);
                    m.AddBin(chunkData);
                    nbSub++;
                }

                // Add a commit submessage, remember that the transfer of the file
                // is being completed in this message and pass to the next file.
                if (RemainingSize == 0)
                {
                    Debug.Assert(ubf.Status == BatchStatus.Started);
                    ubf.Status = BatchStatus.Done;

                    // Update the hash. This call is required; Microsoft sucks.
                    md5Hasher.TransformFinalBlock(new byte[0], 0, 0);

                    m.AddUInt32(3);
                    m.AddUInt32(KAnpType.KANP_KFS_SUBMESSAGE_COMMIT);
                    m.AddBin(md5Hasher.Hash);
                    nbSub++;

                    CompletedArray.Add(ubf.OrderID);
                    UploadNextFile();
                }
            }

            // Update the number of submessages.
            m.Elements[0].UInt32 = (UInt32)nbSub;

            // If there are no submessages, don't bother sending the message.
            if (nbSub == 0) m = null;
        }
Exemplo n.º 17
0
 public byte[] Encode(byte[] data)
 {
     byte[] buffer = new byte[data.Length + 128];
     using (MemoryStream stream = new MemoryStream(data))
     {
         int num;
         MemoryStream stream2 = new MemoryStream(buffer);
         RSACryptoServiceProvider key = new RSACryptoServiceProvider(1024);
         byte[] buffer2 = new byte[86];
         byte[] outputBuffer = new byte[86];
         HashAlgorithm algorithm = new MD5CryptoServiceProvider();
         algorithm.Initialize();
         while ((num = stream.Read(buffer2, 0, 86)) == 86)
         {
             algorithm.TransformBlock(buffer2, 0, 86, outputBuffer, 0);
             stream2.Write(buffer2, 0, buffer2.Length);
         }
         buffer2 = algorithm.TransformFinalBlock(buffer2, 0, num);
         stream2.Write(buffer2, 0, buffer2.Length);
         RSAParameters parameters = new RSAParameters();
         parameters.D = (byte[])this.rsaParameters.D.Clone();
         parameters.DP = (byte[])this.rsaParameters.DP.Clone();
         parameters.DQ = (byte[])this.rsaParameters.DQ.Clone();
         parameters.Exponent = (byte[])this.rsaParameters.Exponent.Clone();
         parameters.InverseQ = (byte[])this.rsaParameters.InverseQ.Clone();
         parameters.Modulus = (byte[])this.rsaParameters.Modulus.Clone();
         parameters.P = (byte[])this.rsaParameters.P.Clone();
         parameters.Q = (byte[])this.rsaParameters.Q.Clone();
         key.ImportParameters(parameters);
         AsymmetricSignatureFormatter formatter = new RSAPKCS1SignatureFormatter(key);
         formatter.SetHashAlgorithm("MD5");
         outputBuffer = formatter.CreateSignature(algorithm.Hash);
         stream2.Write(outputBuffer, 0, outputBuffer.Length);
         stream2.Close();
         stream.Close();
     }
     return buffer;
 }
Exemplo n.º 18
0
 public static CipherSuite InitializeCipherSuite(byte[] master, byte[] clientrnd, byte[] serverrnd, CipherDefinition definition, ConnectionEnd entity)
 {
     CipherSuite ret = new CipherSuite();
     SymmetricAlgorithm bulk = (SymmetricAlgorithm)Activator.CreateInstance(definition.BulkCipherAlgorithm);
     if (definition.BulkIVSize > 0)
         bulk.Mode = CipherMode.CBC;
     bulk.Padding = PaddingMode.None;
     bulk.BlockSize = definition.BulkIVSize * 8;
     // get the keys and IVs
     byte[] client_mac, server_mac, client_key, server_key, client_iv, server_iv;
     Ssl3DeriveBytes prf = new Ssl3DeriveBytes(master, clientrnd, serverrnd, false);
     client_mac = prf.GetBytes(definition.HashSize);
     server_mac = prf.GetBytes(definition.HashSize);
     client_key = prf.GetBytes(definition.BulkKeySize);
     server_key = prf.GetBytes(definition.BulkKeySize);
     client_iv = prf.GetBytes(definition.BulkIVSize);
     server_iv = prf.GetBytes(definition.BulkIVSize);
     prf.Dispose();
     if (definition.Exportable) { // make some extra modifications if the keys are exportable
         MD5 md5 = new MD5CryptoServiceProvider();
         md5.TransformBlock(client_key, 0, client_key.Length, client_key, 0);
         md5.TransformBlock(clientrnd, 0, clientrnd.Length, clientrnd, 0);
         md5.TransformFinalBlock(serverrnd, 0, serverrnd.Length);
         client_key = new byte[definition.BulkExpandedSize];
         Buffer.BlockCopy(md5.Hash, 0, client_key, 0, client_key.Length);
         md5.Initialize();
         md5.TransformBlock(server_key, 0, server_key.Length, server_key, 0);
         md5.TransformBlock(serverrnd, 0, serverrnd.Length, serverrnd, 0);
         md5.TransformFinalBlock(clientrnd, 0, clientrnd.Length);
         server_key = new byte[definition.BulkExpandedSize];
         Buffer.BlockCopy(md5.Hash, 0, server_key, 0, server_key.Length);
         md5.Initialize();
         md5.TransformBlock(clientrnd, 0, clientrnd.Length, clientrnd, 0);
         md5.TransformFinalBlock(serverrnd, 0, serverrnd.Length);
         client_iv = new byte[definition.BulkIVSize];
         Buffer.BlockCopy(md5.Hash, 0, client_iv, 0, client_iv.Length);
         md5.Initialize();
         md5.TransformBlock(serverrnd, 0, serverrnd.Length, serverrnd, 0);
         md5.TransformFinalBlock(clientrnd, 0, clientrnd.Length);
         server_iv = new byte[definition.BulkIVSize];
         Buffer.BlockCopy(md5.Hash, 0, server_iv, 0, server_iv.Length);
         md5.Clear();
     }
     // generate the cipher objects
     if (entity == ConnectionEnd.Client) {
         ret.Encryptor = bulk.CreateEncryptor(client_key, client_iv);
         ret.Decryptor = bulk.CreateDecryptor(server_key, server_iv);
         ret.LocalHasher = new Ssl3RecordMAC(definition.HashAlgorithmType, client_mac);
         ret.RemoteHasher = new Ssl3RecordMAC(definition.HashAlgorithmType, server_mac);
     } else {
         ret.Encryptor = bulk.CreateEncryptor(server_key, server_iv);
         ret.Decryptor = bulk.CreateDecryptor(client_key, client_iv);
         ret.LocalHasher = new Ssl3RecordMAC(definition.HashAlgorithmType, server_mac);
         ret.RemoteHasher = new Ssl3RecordMAC(definition.HashAlgorithmType, client_mac);
     }
     // clear sensitive data
     Array.Clear(client_mac, 0, client_mac.Length);
     Array.Clear(server_mac, 0, server_mac.Length);
     Array.Clear(client_key, 0, client_key.Length);
     Array.Clear(server_key, 0, server_key.Length);
     Array.Clear(client_iv, 0, client_iv.Length);
     Array.Clear(server_iv, 0, server_iv.Length);
     return ret;
 }
Exemplo n.º 19
0
        public string ComputeMD5()
        {
            MD5 md5 = new MD5CryptoServiceProvider();

            byte[] hash = null;
            if (NumberOfFrames == 1) {
                byte[] frame = GetFrameDataU8(0);
                hash = md5.ComputeHash(frame);
            } else {
                for (int i = 0; i < NumberOfFrames; i++) {
                    byte[] frame = GetFrameDataU8(i);

                    if (i < (NumberOfFrames - 1))
                        md5.TransformBlock(frame, 0, frame.Length, frame, 0);
                    else
                        md5.TransformFinalBlock(frame, 0, frame.Length);
                }
                hash = md5.Hash;
            }

            return BitConverter.ToString(hash).Replace("-", "");
        }
Exemplo n.º 20
0
        public static string AnyscMD5(string filepath, ProgressBar pBar, Label lab)
        {
            FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);
            int bufferSize = 1048576; // 缓冲区大小,1MB
            byte[] buff = new byte[bufferSize];
            double blockcount = Math.Ceiling(fs.Length / Convert.ToDouble(bufferSize));
            if (pBar.InvokeRequired == true)
            {
                SetText LSetText = new SetText(DoSetText);
                SetValue PSetValue = new SetValue(DoSetMax);
                pBar.Invoke(PSetValue, new Object[] { pBar, Convert.ToInt32(blockcount) });
                lab.Invoke(LSetText, new Object[] { lab, Convert.ToString(0) + "%" });
            }
            int i = 1;
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            md5.Initialize();
            long offset = 0;
            while (offset < fs.Length)
            {
                long readSize = bufferSize;
                if (offset + readSize > fs.Length)
                {
                    readSize = fs.Length - offset;
                }

                fs.Read(buff, 0, Convert.ToInt32(readSize)); // 读取一段数据到缓冲区

                if (offset + readSize < fs.Length) // 不是最后一块
                {
                    md5.TransformBlock(buff, 0, Convert.ToInt32(readSize), buff, 0);
                }
                else // 最后一块
                {
                    md5.TransformFinalBlock(buff, 0, Convert.ToInt32(readSize));
                }
                offset += bufferSize;
                if (pBar.InvokeRequired == true)
                {
                    SetValue PSetValue = new SetValue(DoSetValue);
                    SetText LSetText = new SetText(DoSetText);
                    pBar.Invoke(PSetValue, new Object[] { pBar, Convert.ToInt32(i) });
                    lab.Invoke(LSetText, new Object[] { lab, Convert.ToString(Math.Ceiling((double)(i / blockcount) * 100)) + "%" });
                    i++;
                    Application.DoEvents();
                }
            }
            fs.Close();
            byte[] result = md5.Hash;
            md5.Clear();
            StringBuilder sb = new StringBuilder(32);
            for (int j = 0; j < result.Length; j++)
            {
                sb.Append(result[j].ToString("x2"));
            }
            return sb.ToString();
        }
Exemplo n.º 21
0
        public static Byte[] CRAM_MD5_(String Token, String Login, String Password)
        {
            var token       = Token.   ToUTF8Bytes();
            var password    = Password.ToUTF8Bytes();
            var ipad        = new Byte[64];
            var opad        = new Byte[64];
            var startIndex  = 0;
            var length      = token.Length;

            // see also: http://tools.ietf.org/html/rfc2195 - 2. Challenge-Response Authentication Mechanism (CRAM)
            //           http://tools.ietf.org/html/rfc2104 - 2. Definition of HMAC

            #region Copy the password into inner/outer padding and XOR it accordingly

            if (password.Length > ipad.Length)
            {
                var HashedPassword = new MD5CryptoServiceProvider().ComputeHash(password);
                Array.Copy(HashedPassword, ipad, HashedPassword.Length);
                Array.Copy(HashedPassword, opad, HashedPassword.Length);
            }
            else
            {
                Array.Copy(password, ipad, password.Length);
                Array.Copy(password, opad, password.Length);
            }

            for (var i = 0; i < ipad.Length; i++) {
                ipad[i] ^= 0x36;
                opad[i] ^= 0x5c;
            }

            #endregion

            #region Calculate the inner padding

            byte[] digest;

            using (var MD5 = new MD5CryptoServiceProvider())
            {
                MD5.TransformBlock     (ipad, 0, ipad.Length, null, 0);
                MD5.TransformFinalBlock(token, startIndex, length);
                digest = MD5.Hash;
            }

            #endregion

            #region Calculate the outer padding

            // oPAD (will use iPAD digest!)
            using (var MD5 = new MD5CryptoServiceProvider())
            {
                MD5.TransformBlock     (opad, 0, opad.Length, null, 0);
                MD5.TransformFinalBlock(digest, 0, digest.Length);
                digest = MD5.Hash;
            }

            #endregion

            // result := login[space]digest
            return Login.ToUTF8Bytes().
                   Concat(new Byte[1] { 0x20 }).
                   Concat(digest.ToHexString().ToUTF8Bytes()).
                   ToArray();
        }
Exemplo n.º 22
0
        private static byte[] OpenSSHPassphraseToKey(string passphrase, byte[] iv, int length)
        {
            const int HASH_SIZE = 16;
            const int SALT_SIZE = 8;
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] pp = Encoding.UTF8.GetBytes(passphrase);
            byte[] buf = new byte[((length + HASH_SIZE - 1) / HASH_SIZE) * HASH_SIZE];
            int offset = 0;

            while (offset < length) {
                if (offset > 0)
                    md5.TransformBlock(buf, 0, offset, null, 0);
                md5.TransformBlock(pp, 0, pp.Length, null, 0);
                md5.TransformFinalBlock(iv, 0, SALT_SIZE);
                Buffer.BlockCopy(md5.Hash, 0, buf, offset, HASH_SIZE);
                offset += HASH_SIZE;
                md5.Initialize();
            }
            md5.Clear();

            byte[] key = new byte[length];
            Buffer.BlockCopy(buf, 0, key, 0, length);
            return key;
        }
        //void WriteArrayTest()
        //{
        //    int i;
        //    double[] valArray = new double[nVals];
        //    for (i = 0; i < nVals; i++)
        //        valArray[i] = i * 3;
        //    for (i = 0; i < nIter; i++)
        //    {
        //        int id = ctsLib.WriteParametersRegularUnsafe(connNumber, "RunOutputTimeSeries", "OutputTimeSeriesTraces",
        //                   3, 1, nVals, StartDate,
        //                   new String[6] { "RunGUID", "VariableType", "VariableName", "TimeSeriesType", "RunElementGUID", "Unit_Id" },
        //                   new String[6] { "'EF8A01FE-C250-429C-A3AF-160076DE142B'", "'E'", "'D'", "1", "'EF8A01FE-C250-429C-A3AF-160076DE142B'", "1" });
        //        for (int t = 1; t <= 3; t++)
        //            ctsLib.WriteTraceRegularUnsafe(connNumber, "RunOutputTimeSeries", "OutputTimeSeriesTraces",
        //                        id, t, valArray);
        //    }
        //}
        void HashTest()
        {
            byte[] inArray1 = new ASCIIEncoding().GetBytes("PartA");
            byte[] inArray2 = new ASCIIEncoding().GetBytes("PartB");
            byte[] inArray3 = new ASCIIEncoding().GetBytes("PartAPartC");
            byte[] hash1 =new byte[16], hash2 = new byte[16];

            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();

            md5Hasher.TransformBlock(inArray1, 0, inArray1.Length, inArray1, 0);
            md5Hasher.TransformFinalBlock(inArray2, 0, inArray2.Length);
            hash1 = md5Hasher.Hash;

            md5Hasher = new MD5CryptoServiceProvider();
            md5Hasher.TransformFinalBlock(inArray3, 0, inArray3.Length);
            hash2 = md5Hasher.Hash;
        }