コード例 #1
0
ファイル: LoginScript.cs プロジェクト: skawafuchi/Swarch
    //The following method was taken straight from the documentation
    static string GetMd5Hash(MD5 md5Hash, string input)
    {
        // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
    }
コード例 #2
0
        private static string CalculateMD5Hash(string input)
        {
            MD5 md5Hash = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return(sBuilder.ToString());
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: Schekaf/WatsonTcp
        private static string Md5(string data)
        {
            if (String.IsNullOrEmpty(data))
            {
                return(null);
            }

            MD5 md5 = MD5.Create();

            byte[]        dataBytes = System.Text.Encoding.ASCII.GetBytes(data);
            byte[]        hash      = md5.ComputeHash(dataBytes);
            StringBuilder sb        = new StringBuilder();

            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("X2"));
            }
            string ret = sb.ToString();

            return(ret);
        }
コード例 #4
0
        public string CalculateMD5Hash(string input)

        {
            // step 1, calculate MD5 hash from input
            MD5 md5 = MD5.Create();

            byte[] inputBytes = Encoding.UTF8.GetBytes(input);

            byte[] hash = md5.ComputeHash(inputBytes);


            // step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();

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

            return(sb.ToString());
        }
コード例 #5
0
        /// <summary>
        /// 32位MD5加密(大写)
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public string MD5Encrypt32_utf8(string password)
        {
            DateTime date = DateTime.Now;

            //10分钟buffer,避免因服务器时间不一致导致密码不对
            if (date.Hour >= 23 && date.Minute > 50)
            {
                date = date.AddDays(1);
            }
            string pwd = "";
            MD5    md  = MD5.Create();                                   //实例化一个md5对像

            byte[] s = md.ComputeHash(Encoding.UTF8.GetBytes(password)); // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
            // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
            for (int i = 0; i < s.Length; i++)
            {
                // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符
                pwd = pwd + s[i].ToString("X2"); //"X"和"X2"有区别,"X"两个0相连的时候可以会少一位
            }
            return(pwd);
        }
コード例 #6
0
        /// <summary>
        /// Criptografa uma string (MD5) e retorna o resultado
        /// </summary>
        /// <param name="input">String de entrada</param>
        /// <returns>String encriptada</returns>
        public static string MD5Encrypt(string inp)
        {
            MD5 md5Hasher = MD5.Create();

            string input = "d5aw8e9d4D8SW89d" + inp + "DS84dsa8d418das6dwe8";

            // Criptografa
            byte[] valorCriptografado = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

            // Cria um StringBuilder para passarmos os bytes gerados para ele
            StringBuilder strBuilder = new StringBuilder();

            // Converte cada byte em um valor hexadecimal e adiciona ao string builder
            for (int i = 0; i < valorCriptografado.Length; i++)
            {
                strBuilder.Append(valorCriptografado[i].ToString("x2"));
            }

            // retorna o valor criptografado
            return(strBuilder.ToString().ToUpper());
        }
コード例 #7
0
 static String GetMD5String(String file)
 {
     if (file == LastFile)
     {
         return(MD5String);
     }
     if (File.Exists(file))
     {
         FileStream stream = File.OpenRead(file);
         MD5        md5    = MD5.Create();
         byte[]     hash   = md5.ComputeHash(stream);
         stream.Close();
         MD5String = BitConverter.ToString(hash);
         LastFile  = file;
         return(MD5String);
     }
     else
     {
         return(null);
     }
 }
コード例 #8
0
ファイル: MD5Hepler.cs プロジェクト: geekkeeper/iODS
        /// <summary>
        /// 32位MD5加密
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string Md5Encrypt32(string password = "")
        {
            string pwd = string.Empty;

            try
            {
                if (!string.IsNullOrEmpty(password) && !string.IsNullOrWhiteSpace(password))
                {
                    MD5 md5 = MD5.Create(); //实例化一个md5对像
                    // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
                    byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
                    // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
                    pwd = s.Aggregate(pwd, (current, item) => string.Concat(current, item.ToString("X")));
                }
            }
            catch
            {
                throw new Exception($"错误的 password 字符串:【{password}】");
            }
            return(pwd);
        }
コード例 #9
0
ファイル: OsuHelper.cs プロジェクト: MinisBett/rxhddt
        public static string HashString(string input)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(input);
            MD5    md5   = MD5.Create();

            byte[] hash;
            try
            {
                hash = md5.ComputeHash(bytes);
            }
            catch
            {
                return("fail");
            }
            char[] destination = new char[hash.Length * 2];
            for (int index = 0; index < hash.Length; ++index)
            {
                hash[index].ToString("x2", new CultureInfo("en-US", false).NumberFormat).CopyTo(0, destination, index * 2, 2);
            }
            return(new string(destination));
        }
コード例 #10
0
ファイル: ObjectUtils.cs プロジェクト: kkdevs/UtinyRipper
        public static UtinyGUID CalculateObjectsGUID(IEnumerable <Object> objects)
        {
            List <uint> hashList = new List <uint>();

            foreach (Object @object in objects)
            {
                hashList.Add(@object.GUID.Data0);
                hashList.Add(@object.GUID.Data1);
                hashList.Add(@object.GUID.Data2);
                hashList.Add(@object.GUID.Data3);
            }

            uint[] hashArray = hashList.ToArray();
            byte[] buffer    = new byte[hashArray.Length * sizeof(uint)];
            Buffer.BlockCopy(hashArray, 0, buffer, 0, buffer.Length);
            using (MD5 md5 = MD5.Create())
            {
                byte[] hash = md5.ComputeHash(buffer);
                return(new UtinyGUID(hash));
            }
        }
コード例 #11
0
ファイル: Hash.cs プロジェクト: xeechaun/Randy
        //****************************//
        public static string MD5(byte[] input)
        {
            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            using (MD5 md5Hash = System.Security.Cryptography.MD5.Create())
            {
                // Convert the input string to a byte array and compute the hash.
                byte[] data = md5Hash.ComputeHash(input);

                // Loop through each byte of the hashed data
                // and format each one as a hexadecimal string.
                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("X2"));
                }
            }
            // Return the hexadecimal string.
            return(sBuilder.ToString());
        }
コード例 #12
0
        static string CalculateMD5Hash(string input)
        {
            // step 1, calculate MD5 hash from input

            MD5 md5 = System.Security.Cryptography.MD5.Create();

            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);

            byte[] hash = md5.ComputeHash(inputBytes);

            // step 2, convert byte array to hex string

            StringBuilder sb = new StringBuilder();

            foreach (byte c in hash)
            {
                sb.Append(c.ToString("X2"));
            }

            return(sb.ToString());
        }
コード例 #13
0
 public ActionResult Edit(Usuario usuario)
 {
     if (ModelState.IsValid)
     {
         if (usuario.nombreUsuario != "admin")
         {
             MD5 crypto    = MD5.Create();
             var passcryto = Convert.ToBase64String(crypto.ComputeHash(Encoding.UTF8.GetBytes(usuario.pass)));
             usuario.pass            = passcryto;
             db.Entry(usuario).State = EntityState.Modified;
             db.SaveChanges();
         }
         else
         {
             throw new Exception("No se puede modificar este usuario");
         }
         return(RedirectToAction("Index"));
     }
     ViewBag.Rolid = new SelectList(db.Rol, "id", "descripcionRol", usuario.Rolid);
     return(View(usuario));
 }
コード例 #14
0
        //https://player.ddyunp.com/jQuery.min.js?v1.5
        public static string GetVaildM3u8Url(string url)
        {
            //url: https://hls.ddyunp.com/ddyun/id/1/key/playlist.m3u8
            string id  = Regex.Match(url, @"\w{20,}").Value;
            string tm  = Global.GetTimeStamp(false);
            string t   = ((long.Parse(tm) / 0x186a0) * 0x64).ToString();
            string tmp = id + "duoduo" + "1" + t;
            MD5    md5 = MD5.Create();

            byte[]        bs = Encoding.UTF8.GetBytes(tmp);
            byte[]        hs = md5.ComputeHash(bs);
            StringBuilder sb = new StringBuilder();

            foreach (byte b in hs)
            {
                sb.Append(b.ToString("x2"));
            }
            string key = sb.ToString();

            return(Regex.Replace(url, @"1/\w{20,}", "1/" + key));
        }
コード例 #15
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            string input = TextBox1.Text;
            MD5    md5   = System.Security.Cryptography.MD5.Create();

            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);

            byte[] hash = md5.ComputeHash(inputBytes);

            // step 2, convert byte array to hex string

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < hash.Length; i++)

            {
                sb.Append(hash[i].ToString("x2"));
            }

            Response.Write(sb.ToString());
        }
コード例 #16
0
        public static string HashEmailForGravatar(string email)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(email));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            return(sBuilder.ToString());  // Return the hexadecimal string.
        }
コード例 #17
0
        public static string GetMD5(string myString)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.GetEncoding("UTF-8").GetBytes(myString));
            // return BitConverter.ToString(data);//可以直接使用这个方法
            //  Create a new Stringbuilder to collect the bytes
            //  and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            // Return the hexadecimal string.
            return(sBuilder.ToString());
        }
コード例 #18
0
        public IActionResult Getodrer(string openid, OrderStateType state)
        {
            #region ---MD5加密Openid
            string Openid = "";
            MD5    md5    = MD5.Create();
            byte[] s      = md5.ComputeHash(Encoding.UTF8.GetBytes(openid));
            for (int i = 0; i < s.Length; i++)
            {
                Openid = Openid + s[i].ToString("X");
            }
            #endregion

            var result = from a in _context.UserApp
                         where a.UserAppOpenid == Openid
                         select a;
            int Code = 0;
            foreach (var item in result)
            {
                Code = item.UserAppCode;
            }
            try
            {
                var odrerdetail = from a in _context.GoodsOrders
                                  where a.UserAppCode == Code && a.UserOrdersState == state
                                  select a;
                List <int> GoodsInfoCode = new List <int> {
                };
                foreach (var item in odrerdetail)
                {
                    GoodsInfoCode.Add(item.GoodsInfoCode);
                }
                ;
                var odrergoodsinfo = _context.GoodsInfo.Where(b => GoodsInfoCode.Contains(b.GoodsInfoCode)).ToList();
                return(Json(odrergoodsinfo));
            }
            catch (Exception)
            {
                return(Content("获取失败"));
            }
        }
コード例 #19
0
        public void Run()
        {
            Console.WriteLine("Decrypting..");
            string password1 = "";

            string[] password2      = new string[8];
            int      foundPassword2 = 0;

            using (MD5 hasher = MD5.Create())
            {
                for (int i = 0; foundPassword2 < 8 || password1.Length < 8; i++)
                {
                    byte[] result = hasher.ComputeHash(Encoding.UTF8.GetBytes(doorID + i.ToString()));
                    string hex    = BitConverter.ToString(result).Replace("-", "");

                    if (hex.StartsWith("00000"))
                    {
                        ///5A
                        if (password1.Length < 8)
                        {
                            password1 += hex[5];
                        }

                        ///5B
                        int  pos;
                        char ch = hex[5];
                        if (int.TryParse(ch.ToString(), out pos))
                        {
                            if (pos >= 0 && pos < 8 && password2[pos] == null)
                            {
                                password2[pos] = hex[6].ToString();
                                foundPassword2++;
                            }
                        }
                    }
                }
            }
            Console.WriteLine("5A: " + password1);
            Console.WriteLine("5B: " + String.Join("", password2));
        }
コード例 #20
0
    private static void TagtoolProc_OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        try
        {
            Logger.Trace("Detect tag: " + (e.Data ?? "").Substring(0, 9) + "...");
            Debug.Trace("Raw data  : " + e.Data); // 生の ID はデバッグ時のみ

            var hashedBytes = _MD5.ComputeHash(Encoding.ASCII.GetBytes(e.Data + ":" + AppSettings.Salt));
            var hashedText  = string.Join("", hashedBytes.Select(n => n.ToString("x2")));
            Logger.Trace(hashedText);

            // 開錠許可されている、登録済の NFC タグかどうか判定
            var isAuthorized = AppSettings.AuthorizedKeys
                               .Split(',')
                               .Any(key => key == hashedText);
            Logger.Trace($"IsAuthorized: {isAuthorized}");

            // NFCタグ検出音を再生
            PlayDetectNFCTagSound(isAuthorized);

            if (isAuthorized)
            {
                Logger.Trace("UNLOCK");
                Gpio21.Value = 1;
                SetState(HostState.Unlocked);
            }
            else
            {
                Gpio21.Value = 0;
                SetState(HostState.Rejected);
            }

            UnlockTimer.Stop();
            UnlockTimer.Start();
        }
        catch (Exception exception)
        {
            Logger.Error(exception);
        }
    }
コード例 #21
0
        private void btn_singup_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["newcon"].ConnectionString);

            try
            {
                if (txtBox_signup_username.Text != null && txtBox_signup_fullname.Text != null && txtBox_signup_pass.Text != null && txtBox_signup_retypePass != null && (txtBox_signup_pass == txtBox_signup_retypePass) && txtBox_signup_Add != null && txtBox_signup_SQ != null && txtBox_signup_SA != null)
                {
                    MessageBox.Show("You have Validated All of the Criterias Above and now You will be Signed Up ");
                }

                byte[]       img = null;
                FileStream   fs  = new FileStream(imglocation, FileMode.Open, FileAccess.Read);
                BinaryReader br  = new BinaryReader(fs);
                img = br.ReadBytes((int)fs.Length);

                conn.Open();
                SqlCommand cmd = new SqlCommand("insert into [loginuser] (username,password,fullname,address,sq,sa,image) values (@username,@pass,@full,@add,@sq,@sa,@img)", conn);
                cmd.Parameters.AddWithValue("username", txtBox_signup_username.Text);
                cmd.Parameters.AddWithValue("pass", md5Hash.ComputeHash(Encoding.UTF8.GetBytes(txtBox_signup_pass.Text)));
                cmd.Parameters.AddWithValue("full", txtBox_signup_fullname.Text);
                cmd.Parameters.AddWithValue("add", txtBox_signup_Add.Text);
                cmd.Parameters.AddWithValue("sq", txtBox_signup_SQ.Text);
                cmd.Parameters.AddWithValue("sa", txtBox_signup_SA.Text);
                cmd.Parameters.AddWithValue("img", img);
                MessageBox.Show("Account Created Sucessfully");
                cmd.ExecuteReader();
                conn.Close();
                this.Close();
                //AdminLogin admin_login_obj = new AdminLogin();
                //admin_login_obj.ShowDialog();
            } //End of Try
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally {
                conn.Close();
            }
        }
コード例 #22
0
ファイル: MD5Encrypt.cs プロジェクト: baby-Jie/MyTools
        public static string GetEncrptStringByMD5(string source, int length = 32)
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                MD5    md5      = MD5.Create();
                byte[] srcBytes = Encoding.UTF8.GetBytes(source);
                byte[] outBytes = md5.ComputeHash(srcBytes);

                switch (length)
                {
                case 16:
                    for (int i = 4; i < 12; i++)
                    {
                        sb.Append(outBytes[i].ToString("X2"));
                    }
                    break;

                case 32:
                    for (int i = 0; i < 16; i++)
                    {
                        sb.Append(outBytes[i].ToString("X2"));
                    }
                    break;

                default:
                    for (int i = 0; i < outBytes.Length; i++)
                    {
                        sb.Append(outBytes[i].ToString("X2"));
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex.Message);
            }
            return(sb.ToString());
        }
コード例 #23
0
ファイル: V4Authenticator.cs プロジェクト: jflzbest/C-
        /// <summary>
        /// Set 'Content-MD5' http header.
        /// </summary>
        /// <param name="request">Instantiated request object</param>
        private void SetContentMd5(IRestRequest request)
        {
            if (request.Method == Method.PUT || request.Method.Equals(Method.POST))
            {
                var bodyParameter = request.Parameters.Where(p => p.Type.Equals(ParameterType.RequestBody)).FirstOrDefault();
                if (bodyParameter == null)
                {
                    return;
                }
                bool isMultiDeleteRequest = false;
                if (request.Method == Method.POST && request.Resource.EndsWith("?delete"))
                {
                    isMultiDeleteRequest = true;
                }
                // For insecure, authenticated requests set sha256 header instead of MD5.
                if (!isSecure && !isAnonymous && !isMultiDeleteRequest)
                {
                    return;
                }
                // All anonymous access requests get Content-MD5 header set.
                byte[] body = null;
                if (bodyParameter.Value is string)
                {
                    body = System.Text.Encoding.UTF8.GetBytes(bodyParameter.Value as string);
                }
                if (bodyParameter.Value is byte[])
                {
                    body = bodyParameter.Value as byte[];
                }
                if (body == null)
                {
                    body = new byte[0];
                }
                MD5    md5  = System.Security.Cryptography.MD5.Create();
                byte[] hash = md5.ComputeHash(body);

                string base64 = Convert.ToBase64String(hash);
                request.AddHeader("Content-MD5", base64);
            }
        }
コード例 #24
0
        public string ComputeHashMd5(string value, string salt)
        {
            if (salt.IsNullOrEmpaty())
            {
                throw new InvalidOperationException("Salt not found");
            }

            if (string.IsNullOrEmpty(value))
            {
                return(string.Empty);
            }

            using (var tripleDES = TripleDES.Create())
            {
                byte[]       Results;
                UTF8Encoding UTF8 = new UTF8Encoding();
                MD5          MD5  = MD5.Create();

                byte[] TDESKey = MD5.ComputeHash(UTF8.GetBytes(salt));

                if (TDESKey.Length == 16)
                {
                    byte[] keyTemp = new byte[24];
                    Buffer.BlockCopy(TDESKey, 0, keyTemp, 0, TDESKey.Length);
                    Buffer.BlockCopy(TDESKey, 0, keyTemp, TDESKey.Length, 8);
                    TDESKey = keyTemp;
                }

                tripleDES.Key     = TDESKey;
                tripleDES.Mode    = CipherMode.ECB;
                tripleDES.Padding = PaddingMode.PKCS7;

                byte[] DataToEncrypt = UTF8.GetBytes(value);

                ICryptoTransform Encryptor = tripleDES.CreateEncryptor();
                Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);

                return(Convert.ToBase64String(Results));
            }
        }
コード例 #25
0
        // From https://github.com/codetheweb/tuyapi/blob/master/index.js#L300
        byte[] EncryptedBytesFromJSONForDevice(string JSON, Device device)
        {
            Log.Format("Request.EncryptedBytesFromJSONForDevice()");

            // Key.
            byte[] key = Encoding.UTF8.GetBytes(device.localKey);

            // Encrypt with key.
            string encryptedJSONBase64String;

            using (AesManaged aes = new AesManaged()
            {
                Mode = CipherMode.ECB, Key = key
            })
                using (MemoryStream encryptedStream = new MemoryStream())
                    using (CryptoStream cryptoStream = new CryptoStream(encryptedStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        byte[] JSONBytes = Encoding.UTF8.GetBytes(JSON);
                        cryptoStream.Write(JSONBytes, 0, JSONBytes.Length);
                        cryptoStream.Close();
                        encryptedJSONBase64String = Convert.ToBase64String(encryptedStream.ToArray());
                    }

            // Create hash.
            string hashString;

            using (MD5 md5 = MD5.Create())
                using (MemoryStream hashBaseStream = new MemoryStream())
                {
                    byte[] encryptedPayload = Encoding.UTF8.GetBytes($"data={encryptedJSONBase64String}||lpv={device.protocolVersion}||");
                    hashBaseStream.Write(encryptedPayload, 0, encryptedPayload.Length);
                    hashBaseStream.Write(key, 0, key.Length);
                    byte[] hashBytes = md5.ComputeHash(hashBaseStream.ToArray());
                    string hash      = BitConverter.ToString(hashBytes).Replace("-", string.Empty).ToLower();
                    hashString = hash.Substring(8, 16);
                }

            // Stitch together.
            return(Encoding.UTF8.GetBytes($"{device.protocolVersion}{hashString}{encryptedJSONBase64String}"));
        }
コード例 #26
0
 private void OnReceive(IAsyncResult ar)
 {
     try
     {
         TimeOutChecker.Stop();
         server.EndReceive(ar);
         //Преобразование массива байтов, полученных от пользователя в удобную для нас форму объекта данных
         DataInfo msgReceived = new DataInfo(byteData);
         int      blocksCount = (int)Math.Ceiling((float)msgReceived.filesize / (float)maxBufferSize); // blockSize);
         if (msgReceived.blockNum == 0)
         {
             currStatus   = string.Format("----Информация о файле получена! Размер файла: {0} байт", msgReceived.filesize);
             fileContents = new byte[msgReceived.filesize];
             checkBlocks  = new Boolean[blocksCount];
             //transferProgressBar.BeginInvoke(new Action(() => transferProgressBar.Maximum = blocksCount));
         }
         MD5 md5Hash = MD5.Create();
         //int blockSize = msgReceived.dataBlock.Length; // client.ReceiveBufferSize;
         byte[] data = new byte[msgReceived.dataBlock.Length];
         //data.Take(packetSize).ToArray().CopyTo(fileContents, i * blockSize);
         if (!HashesEqual(md5Hash.ComputeHash(msgReceived.dataBlock), msgReceived.blockHash))
         {
             currStatus = ("Контрольная сумма блока неверна!");
         }
         else
         {
             msgReceived.dataBlock.CopyTo(fileContents, maxBufferSize * msgReceived.blockNum);
             checkBlocks[msgReceived.blockNum] = true;
         }
         //transferProgressBar.BeginInvoke(new Action(() => transferProgressBar.PerformStep()));
         server.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref senderRemote, new AsyncCallback(OnReceive), null);
         TimeOutChecker.Start();
     }
     catch (ObjectDisposedException)
     { }
     catch (Exception ex)
     {
         Debug.WriteLine("FileTransferClient: " + ex.Message);
     }
 }
コード例 #27
0
        /// <summary>
        /// Generates a unique subscription ID that can be passed to <see cref="LiveCaptureSubscription()"/>
        /// </summary>
        /// <returns>The generated ID.</returns>
        /// <param name="connectionIndex">Client origin.</param>
        /// <param name="equpimentType">Equipment type.</param>
        /// <param name="equipmentIndex">Equipment index to observe.</param>
        public static ulong GenerateSubscriptionID(int connectionIndex, SensorType equpimentType, int equipmentIndex)
        {
            // concat arguments to input array
            byte[] bConnection = BitConverter.GetBytes(connectionIndex);
            byte[] bSensor     = BitConverter.GetBytes((int)equpimentType);
            byte[] bIndex      = BitConverter.GetBytes(equipmentIndex);
            byte[] input       = new byte[bConnection.Length + bSensor.Length + bIndex.Length];
            int    offset      = 0;

            Array.Copy(bConnection, 0, input, offset, bConnection.Length);
            offset += bConnection.Length;
            Array.Copy(bSensor, 0, input, offset, bSensor.Length);
            offset += bSensor.Length;
            Array.Copy(bIndex, 0, input, offset, bIndex.Length);
            // comptute some hash
            byte[] hash;
            using (MD5 md5 = MD5Cng.Create()) {
                hash = md5.ComputeHash(input);
            }
            // reduce the hash to a shorter value
            ulong checkSum = 0x0;

            if (hash.Length < sizeof(ulong))
            {
                // fail safe
                // generate something if the hash is somehow very short
                for (int i = 0; i < hash.Length; i++)
                {
                    checkSum |= ((ulong)hash[i] << (8 * i));
                }
                return(checkSum);
            }

            for (int i = 0; i + sizeof(ulong) <= hash.Length; i += sizeof(ulong))
            {
                checkSum ^= BitConverter.ToUInt64(hash, i);
            }

            return(checkSum);
        }
コード例 #28
0
        /// <summary>
        /// Returns the central 8 bytes of the hash result of the input string.
        /// </summary>
        public static bool EqualsCredential(this string credential, string id, string pass)
        {
            if (credential == null || credential.Length != 32)
            {
                return(false);
            }

            // convert to bytea, assume ascii
            int idlen   = id.Length;
            int passlen = pass.Length;
            int len     = idlen + passlen + 1;

            byte[] raw = new byte[len];
            int    p   = 0;

            for (int i = 0; i < idlen; i++)
            {
                raw[p++] = (byte)id[i];
            }
            raw[p++] = (byte)':';
            for (int i = 0; i < passlen; i++)
            {
                raw[p++] = (byte)pass[i];
            }

            // digest and transform
            using (MD5 md5 = System.Security.Cryptography.MD5.Create())
            {
                byte[] hash = md5.ComputeHash(raw);
                for (int i = 0; i < 16; i++)
                {
                    byte b = hash[i];
                    if (credential[i * 2] != HEX[b >> 4] || credential[i * 2 + 1] != HEX[b & 0x0f])
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
コード例 #29
0
ファイル: USAePay.cs プロジェクト: giagiigi/WE
        private GatewayUSAePay.USAePaySOAP.ueSecurityToken GetSecurityToken()
        {
            //make ueSecurityToken - wiki.usaepay.com/developer/soap-1.6/howto/csharp
            var token = new GatewayUSAePay.USAePaySOAP.ueSecurityToken();

            token.SourceKey    = SourceKey;
            token.ClientIP     = CommonLogic.CustomerIpAddress();
            token.PinHash      = new GatewayUSAePay.USAePaySOAP.ueHash();
            token.PinHash.Seed = Guid.NewGuid().ToString();             //can hardcode a number like 1234 for debug
            token.PinHash.Type = "md5";

            String preHashValue = String.Empty;

            preHashValue = token.SourceKey + token.PinHash.Seed + Pin;

            #region CalculateMD5

            // step 1, calculate MD5 hash from input
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(preHashValue));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2", CultureInfo.InvariantCulture));
            }

            #endregion

            token.PinHash.HashValue = sBuilder.ToString();
            return(token);
        }
コード例 #30
0
        private byte[] hash(byte[] src)
        {
            uint _loc2_ = Convert.ToUInt32(src.Length * 8);

            while (src.Length % 4 != 0)
            {
                List <byte> list = src.ToList();
                list.RemoveAt(src.Length - 1);
                src = list.ToArray();
            }
            List <uint> _loc4_ = new List <uint>();
            uint        _loc5_ = 0;

            byte[] _loc6_;
            using (MD5 md5Hash = MD5.Create())
            {
                _loc6_ = md5Hash.ComputeHash(src.ToArray());
            }
            BinaryReader reader = new BinaryReader(new MemoryStream(_loc6_), Encoding.UTF8);

            while (_loc5_ < _loc6_.Length)
            {
                _loc4_.Add(reader.ReadUInt32());
                _loc5_ = _loc5_ + 4;
            }
            BinaryWriter writer = new BinaryWriter(new MemoryStream(), Encoding.Default);

            _loc5_ = 0;
            while (_loc5_ < 4)
            {
                writer.Write(_loc4_.ToArray()[_loc5_]);
                _loc5_++;
            }
            byte[] content = new byte[writer.BaseStream.Length];

            writer.BaseStream.Position = 0;
            writer.BaseStream.Read(content, 0, (int)writer.BaseStream.Length);

            return(content);
        }
コード例 #31
0
ファイル: day5.cs プロジェクト: adagr/Advent-of-Code
        static public void part1()
        {
            MD5         md5 = MD5.Create();
            int         index = 0, count = 0;
            List <char> password = new List <char>();

            while (true)
            {
                byte[]        inputBytes = Encoding.ASCII.GetBytes("abbhdwsy" + index);
                byte[]        hash       = md5.ComputeHash(inputBytes);
                StringBuilder sb         = new StringBuilder();
                for (int i = 0; i < hash.Length; i++)
                {
                    sb.Append(hash[i].ToString("X2"));
                }
                string s = sb.ToString();
                if (s.Substring(0, 5) == "00000")
                {
                    count++;
                    password.Add(s[5]);
                }

                if (index % 10000 == 0)
                {
                    for (int i = 0; i < 8; i++)
                    {
                        if (i < count)
                        {
                            Console.Write(password[i]);
                        }
                        else
                        {
                            Console.Write(RandomLetter.GetLetter());
                        }
                    }
                    Console.Write("\r");
                }
                index++;
            }
        }
コード例 #32
0
ファイル: YwMd5.cs プロジェクト: 602147629/2DPlatformer-SLua
 /**
  * Computer a md5 hash from a stream.
  * 
  * @param MD5 cMd5 - The md5 instance.
  * @param Stream cStream - The input stream.
  * @return string - The md5 hash.
  */
 private string GetMd5Hash(MD5 cMd5, Stream cStream)
 {
     // Convert the input stream to a byte array and compute the hash.
     byte[] aData = cMd5.ComputeHash(cStream);
     
     // Use a Stringbuilder to collect the bytes
     // and create a string.
     m_cTextBuf.Length = 0;
     
     // Loop through each byte of the hashed data 
     // and format each one as a hexadecimal string.
     for (int i = 0; i < aData.Length; i++)
     {
         m_cTextBuf.Append(aData[i].ToString("x2"));
     }
     
     // Return the hexadecimal string.
     return m_cTextBuf.ToString();
 }