Наследование: HashAlgorithm
Пример #1
0
        public static string MD5(string sourceStr)
        {
            string str = string.Empty;

            System.Security.Cryptography.MD5 md = System.Security.Cryptography.MD5.Create();
            MemoryStream stream = new MemoryStream();
            StreamWriter writer = new StreamWriter(stream);
            StreamReader reader = new StreamReader(stream);

            if (sourceStr == null)
            {
                sourceStr = string.Empty;
            }
            writer.Write(sourceStr);
            writer.Flush();
            stream.Seek(0L, SeekOrigin.Begin);
            byte[] buffer = md.ComputeHash(stream);
            stream.SetLength(0L);
            writer.Flush();
            for (int i = 0; i < buffer.Length; i++)
            {
                writer.Write("{0:X2}", buffer[i]);
            }
            writer.Flush();
            stream.Seek(0L, SeekOrigin.Begin);
            str = reader.ReadToEnd();
            writer.Close();
            writer.Dispose();
            reader.Close();
            reader.Dispose();
            stream.Close();
            stream.Dispose();
            return(str);
        }
Пример #2
0
 public static byte[] MD5(byte[] data)
 {
     using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
     {
         return(ComputeHash(md5, data));
     }
 }
Пример #3
0
        public override byte[] ByteHashAlgorithm(string value)
        {
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] bytes = md5.ComputeHash(System.Text.ASCIIEncoding.UTF8.GetBytes(value));

            return(bytes);
        }
Пример #4
0
    public static bool CheckMD5(string fullPathName, string md5)
    {
        if (!File.Exists(fullPathName))
        {
            return(false);
        }
#if UNITY_IPHONE
        //ios下如果封装该方法在一个函数中,调用该函数来产生文件的MD5的时候,就会抛JIT异常。
        //如果直接把这个产生MD5的方法体放在直接执行,就可以正常执行,这个原因还不清楚。
        string md5Compute = null;
        using (System.IO.FileStream fileStream = System.IO.File.OpenRead(fullPathName))
        {
            System.Security.Cryptography.MD5 md5Tmp = System.Security.Cryptography.MD5.Create();
            byte[] fileMD5Bytes = md5Tmp.ComputeHash(fileStream);
            md5Compute = System.BitConverter.ToString(fileMD5Bytes).Replace("-", "").ToLower();
        }
#else
        var md5Compute = Utils.BuildFileMd5(fullPathName);
#endif
        bool isCheck = md5Compute.Trim() == md5.Trim();
        if (!isCheck)
        {
            Logger.Log("MD5检验失败!: " + md5Compute + " --- " + md5);
        }
        return(isCheck);
    }
Пример #5
0
 public static string sign(string sourceData, string key)
 {
     System.Security.Cryptography.MD5 mD = System.Security.Cryptography.MD5.Create();
     byte[] bytes = System.Text.Encoding.UTF8.GetBytes(sourceData + key);
     byte[] data  = mD.ComputeHash(bytes);
     return(Jiami.GetbyteToString(data));
 }
Пример #6
0
        private static void EvpBytesToKey(string _password, byte[] _salt, out byte[] _key, out byte[] _iv)
        {
            List <byte> _hashes = new List <byte>(48);

            byte[] _passwordBytes = System.Text.Encoding.UTF8.GetBytes(_password);
            byte[] _currentHash   = new byte[0];
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            bool _enoughBytesForKey = false;

            while (!_enoughBytesForKey)
            {
                int    _preHashLength = _currentHash.Length + _passwordBytes.Length + _salt.Length;
                byte[] _preHash       = new byte[_preHashLength];

                Buffer.BlockCopy(_currentHash, 0, _preHash, 0, _currentHash.Length);
                Buffer.BlockCopy(_passwordBytes, 0, _preHash, _currentHash.Length, _passwordBytes.Length);
                Buffer.BlockCopy(_salt, 0, _preHash, _currentHash.Length + _passwordBytes.Length, _salt.Length);

                _currentHash = md5.ComputeHash(_preHash);
                _hashes.AddRange(_currentHash);

                if (_hashes.Count >= 48)
                {
                    _enoughBytesForKey = true;
                }
            }

            _key = new byte[32];
            _iv  = new byte[16];
            _hashes.CopyTo(0, _key, 0, 32);
            _hashes.CopyTo(32, _iv, 0, 16);

            md5.Clear();
            md5 = null;
        }
Пример #7
0
 private static string CalculateChecksum(string path)
 {
     using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
     {
         return(CalculateChecksum(path, md5));
     }
 }
Пример #8
0
        /// <summary>
        /// 解密数据
        /// </summary>
        /// <param name="Text"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string Decrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            int len;

            len = Text.Length / 2;
            byte[] inputByteArray = new byte[len];
            int    x, i;

            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            string AscIIValue = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(sKey))).Replace("-", null).Substring(0, 8);

            des.Key = ASCIIEncoding.ASCII.GetBytes(AscIIValue);
            des.IV  = ASCIIEncoding.ASCII.GetBytes(AscIIValue);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream           cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return(Encoding.Default.GetString(ms.ToArray()));
        }
Пример #9
0
        public void DecryptDSAes(string path, DataSet ds)
        {
            System.Security.Cryptography.MD5 md5Hash = System.Security.Cryptography.MD5.Create();

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

            // Create an AesManaged object
            // with the specified key and IV.
            using (AesManaged aesAlg = new AesManaged())
            {
                aesAlg.Key = data;
                aesAlg.IV  = data;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for decryption.
                using (System.IO.FileStream msDecrypt = new System.IO.FileStream(path, System.IO.FileMode.Open))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        ds.ReadXml(csDecrypt);
                    }
                }
            }
        }
Пример #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Input">來源</param>
        /// <param name="salted">Salted Hash字串</param>
        /// <param name="Half">加密是16位or32位;如果是true為16位</param>
        /// <returns></returns>
        public static string MD5Encrypt(byte[] Input, string salted, bool Half)
        {
            if (salted == null || salted.Length == 0)//如果使用者沒給Salt值,那給預設
            {
                salted = "salted";
            }
            //byte[] Original = Encoding.Default.GetBytes(txt_Source.Text);//將來源字串轉為byte[]
            byte[] SaltValue = Encoding.Default.GetBytes(salted);         //將Salted Value轉為byte[]
            byte[] ToSalt    = new byte[Input.Length + SaltValue.Length]; //宣告新的byte[]來儲存加密後的值
            Input.CopyTo(ToSalt, 0);                                      //將來源字串複製到新byte[]
            SaltValue.CopyTo(ToSalt, Input.Length);                       //將Salted Value複製到新byte[]

            string output = "";

            using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
            {
                byte[] SaltPWD = md5.ComputeHash(ToSalt);                     //進行加密
                byte[] PWD     = new byte[SaltPWD.Length + SaltValue.Length]; //宣告新byte[]儲存加密及Salted的值
                SaltPWD.CopyTo(PWD, 0);                                       //將加密後的值複製到新byte[]
                SaltValue.CopyTo(PWD, SaltPWD.Length);                        //將Salted Value複製到新byte[]
                output = BitConverter.ToString(PWD).Replace("-", String.Empty);
            }

            if (Half)//16位MD5加密(取32位加密的9~25字元)
            {
                output = output.Substring(8, 16);
            }
            return(output);
        }
Пример #11
0
        public string CreateMD5Hash(string input)
        {
            // Use input string to calculate MD5 hash
            StringBuilder sb = new StringBuilder();

            try
            {
                System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
                byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
                byte[] hashBytes  = md5.ComputeHash(inputBytes);

                // Convert the byte array to hexadecimal string

                for (int i = 0; i < hashBytes.Length; i++)
                {
                    sb.Append(hashBytes[i].ToString("X2"));
                    // To force the hex string to lower-case letters instead of
                    // upper-case, use he following line instead:
                    // sb.Append(hashBytes[i].ToString("x2"));
                }
            }
            catch (Exception ex)
            {
                ;
            }
            return(sb.ToString());
        }
Пример #12
0
		private SynchronizingFileStream(ITransactionalStorage transactionalStorage, string fileName,
										StorageStreamAccess storageStreamAccess, NameValueCollection metadata,
										IndexStorage indexStorage, StorageOperationsTask operations)
			: base(transactionalStorage, fileName, storageStreamAccess, metadata, indexStorage, operations)
		{
			md5Hasher = new MD5CryptoServiceProvider();
		}
Пример #13
0
        public async Task DoLogin(string email, string password)
        {
            try {
                Username = email;

                using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
                {
                    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(email);
                    byte[] hashBytes  = md5.ComputeHash(inputBytes);

                    // Convert the byte array to hexadecimal string
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < hashBytes.Length; i++)
                    {
                        sb.Append(hashBytes[i].ToString("X2"));
                    }
                    Gravatar = sb.ToString().ToLower();
                }

                app  = Realms.Sync.App.Create("opkanban-lymqs");
                user = await app.LogInAsync(Realms.Sync.Credentials.EmailPassword(email, password));

                partition = $"user={ user.Id }";
                config    = new Realms.Sync.SyncConfiguration(partition, user);
                realm     = await Realm.GetInstanceAsync(config);

                IsLoggedIn  = true;
                LoginFailed = false;
            } catch (Exception e) {
                IsLoggedIn  = false;
                LoginFailed = true;
            }
            NotifyStateChanged();
        }
Пример #14
0
 /// <summary>
 /// Compute MD5 hash of string
 /// and return a string encoded base64
 /// </summary>
 /// <param name="inputString"></param>
 /// <returns></returns>
 public static string MD5GenerateHash(string inputString)
 {
     System.Security.Cryptography.MD5 hash = System.Security.Cryptography.MD5.Create();
     Byte[] inputBytes  = ASCIIEncoding.Default.GetBytes(inputString);
     Byte[] outputBytes = hash.ComputeHash(inputBytes);
     return(Convert.ToBase64String(outputBytes));
 }
Пример #15
0
 public static string Encode(string str)
 {
     try
     {
         System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
         byte[]        data = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
         StringBuilder sb   = new StringBuilder();
         for (int i = 0; i < data.Length; i++)
         {
             sb.Append(data[i].ToString("x2"));
         }
         int len = 0;
         for (int i = 0; i < sb.Length; i++)
         {
             if (sb[i] != '0')
             {
                 break;
             }
             len++;
         }
         sb.Remove(0, len);
         return(sb.ToString());
     }
     catch
     {
         return(null);
     }
 }
Пример #16
0
        private static string[] HashMeBabyLikeAWagonWheel(string input)
        {
            using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
            {
                string[] suspectedMatch = { "_", "_" };

                byte[]        retVal = md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(input));
                StringBuilder sb     = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }

                if (sb.ToString().StartsWith("00000"))
                {
                    int  n;
                    bool isNumeric = int.TryParse(sb[5].ToString(), out n);

                    if (isNumeric && (n < 8))
                    {
                        suspectedMatch[0] = sb[5].ToString();
                        suspectedMatch[1] = sb[6].ToString();
                    }
                }

                return(suspectedMatch);
            }
        }
Пример #17
0
 public static string Md5Hash(string input)
 {
     byte[] data = Encoding.UTF8.GetBytes(input);
     System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
     byte[] output = md5.ComputeHash(data);
     return(Convert.ToBase64String(output));
 }
Пример #18
0
        public static string GetMD5(string file, Int64 offset, Int64 size)
        {
            string     md5String;
            FileStream fileStream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            long       fileSize   = fileStream.Length;

            fileStream.Seek(offset, SeekOrigin.Begin);

            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            if (size != 0)
            {
                if (fileSize - offset < size)
                {
                    size = fileSize - offset;
                }
                byte[] buffer = new byte[size];
                fileStream.Read(buffer, 0, (int)size);
                MemoryStream ms = new MemoryStream(buffer);
                md5String = BitConverter.ToString(md5.ComputeHash(ms)).Replace("-", String.Empty);
            }
            else
            {
                md5String = BitConverter.ToString(md5.ComputeHash(fileStream)).Replace("-", String.Empty);
            }
            fileStream.Close();
            return(md5String);
        }
        // GET api/<controller>/administrator/administrator
        public string Get([FromUri] ResourceQuery query)
        {
            string nationalCode = query.NationalCode, hashPassword = query.HashedPassword;

            try
            {
                Models.User u = UserRepository.GetInstance().FindByNationalCode(nationalCode);
                using (System.Security.Cryptography.MD5 md5 =
                           System.Security.Cryptography.MD5.Create())
                {
                    byte[]        retVal = md5.ComputeHash(Encoding.Unicode.GetBytes(u.Password));
                    StringBuilder sb     = new StringBuilder();
                    for (int i = 0; i < retVal.Length; i++)
                    {
                        sb.Append(retVal[i].ToString("x2"));
                    }

                    string serial = TicketRepository.GetInstance().Save(u);
                    return(sb.ToString() == hashPassword
                        ? "{'ticket':'" + serial + "'}"
                        : "{'error':'User or password is wrong'}");
                }
            }
            catch (EntityNotFoundException e)
            {
                Log.Info("user not found", e);
                return("User or password is wrong");
            }
        }
Пример #20
0
        public void EncryptStreamAes(string path, System.IO.Stream str)
        {
            System.Security.Cryptography.MD5 md5Hash = System.Security.Cryptography.MD5.Create();

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

            // Create an AesManaged object
            // with the specified key and IV.
            using (AesManaged aesAlg = new AesManaged())
            {
                aesAlg.Key = data;
                aesAlg.IV  = data;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (System.IO.FileStream msEncrypt = new System.IO.FileStream(path, System.IO.FileMode.Create))
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        str.CopyTo(csEncrypt);
                    }
                }
            }
        }
Пример #21
0
        /// <summary>
        ///  计算指定文件的MD5值
        /// </summary>
        /// <param name="fileName">指定文件的完全限定名称</param>
        /// <returns>返回值的字符串形式</returns>
        public static string CreateMD5ByFile(String fileName)
        {
            string hashMD5 = String.Empty;

            //检查文件是否存在,如果文件存在则进行计算,否则返回空值
            if (System.IO.File.Exists(fileName))
            {
                using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    //计算文件的MD5值
                    System.Security.Cryptography.MD5 calculator = System.Security.Cryptography.MD5.Create();
                    Byte[] buffer = calculator.ComputeHash(fs);
                    calculator.Clear();
                    //将字节数组转换成十六进制的字符串形式
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < buffer.Length; i++)
                    {
                        stringBuilder.Append(buffer[i].ToString("x2"));
                    }

                    hashMD5 = stringBuilder.ToString();
                } //关闭文件流
            }     //结束计算

            return(hashMD5);
        }
Пример #22
0
        public static string GetMD5Code(string input)
        {
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] data = md5.ComputeHash(Encoding.Default.GetBytes(input));
            //正常加密  每个数组元素转换16进制数字
            StringBuilder sBuilder = new StringBuilder();

            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            ////混淆加密  每个数组元素转换16进制数字 + henry
            //StringBuilder sBuilder = new StringBuilder();
            //for (int i = 0; i < data.Length; i++)
            //{
            //    sBuilder.Append(data[i].ToString("x2") + "henry");
            //}

            //正常加密  通过BitConverter转换为string类型  但是会生成带“-”符号  用Replace 替换掉
            string output = BitConverter.ToString(data).Replace("-", "");
            //混淆加密 把0替换成L
            string otherput = output.Replace("0", "l");

            return(sBuilder.ToString());
        }
Пример #23
0
        /// <summary>
        /// 获取字符串的特征串
        /// </summary>
        /// <param name="sInputString">输入文本</param>
        /// <returns></returns>
        public static string HashString(string sInputString)
        {
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            string encoded = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(sInputString))).Replace("-", "");

            return(encoded);
        }
 /// <summary>
 /// 返回16进制MD5值
 /// </summary>
 /// <param name="inputString"></param>
 /// <returns></returns>
 public static string GetMD5Value(string inputString)
 {
     byte[] inputBuffer = Encoding.UTF8.GetBytes(inputString);
     System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
     byte[] hashBuffer = md5.ComputeHash(inputBuffer);
     return(BytesToHexString(hashBuffer));
 }
Пример #25
0
 public string CreateMD5Hash2(string input)
 {
     System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
     byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
     byte[] hashBytes  = md5.ComputeHash(inputBytes);
     return(System.BitConverter.ToString(hashBytes).Replace("-", "").ToLower());
 }
Пример #26
0
        public static string GetMd5Hash(string input)
        {
            StringBuilder sBuilder = new StringBuilder();

            using (System.Security.Cryptography.MD5 md5Hash = System.Security.Cryptography.MD5.Create())
            {
                if (input == "" || input == null)
                {
                    input = "chanhniem";
                }
                // 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.


                // 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());
        }
Пример #27
0
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str">加密字符</param>
        /// <param name="code">加密位数16/32</param>
        /// <returns></returns>
        public static string md5(string str, int code = 32)
        {
            string strEncrypt = string.Empty;

            if (code == 16)
            {
                MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                strEncrypt = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(str)), 4, 8);
                strEncrypt = strEncrypt.Replace("-", "").ToLower();
            }

            if (code == 32)
            {
                StringBuilder result = new StringBuilder();
                System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
                byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(str));

                for (int i = 0; i < s.Length; i++)
                {
                    result.Append(s[i].ToString("x"));
                }
                strEncrypt = result.ToString();
            }

            return(strEncrypt);
        }
Пример #28
0
        public string EncryptMD5(string text, bool isLower, int bit)
        {
            string text2 = string.Empty;

            if (bit != 32 && bit != 16)
            {
                return(text2);
            }
            if (bit == 32)
            {
                System.Security.Cryptography.MD5 mD = System.Security.Cryptography.MD5.Create();
                byte[] array = mD.ComputeHash(System.Text.Encoding.UTF8.GetBytes(text));
                for (int i = 0; i < array.Length; i++)
                {
                    text2 += array[i].ToString("X");
                }
            }
            else
            {
                System.Security.Cryptography.MD5CryptoServiceProvider mD5CryptoServiceProvider = new System.Security.Cryptography.MD5CryptoServiceProvider();
                text2 = System.BitConverter.ToString(mD5CryptoServiceProvider.ComputeHash(System.Text.Encoding.Default.GetBytes(text)), 4, 8);
                text2 = text2.Replace("-", "");
            }
            if (isLower)
            {
                text2 = text2.ToLower();
            }
            return(text2);
        }
Пример #29
0
        /// <summary>
        /// MD5编码
        /// </summary>
        /// <param name="value">明文</param>
        /// <param name="bit">位长</param>
        /// <returns></returns>
        public static string Get(string value, MD5Bit bit)
        {
            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            if (bit == MD5Bit.L32)
            {
                // Create a new instance of the MD5CryptoServiceProvider object.
                System.Security.Cryptography.MD5 md5Hasher = System.Security.Cryptography.MD5.Create();

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

                // 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"));
                }
            }
            if (bit == MD5Bit.L16)
            {
                // This is one implementation of the abstract class MD5.
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();

                string temp = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(value)), 4, 8);
                temp = temp.Replace("-", "");
                sBuilder.Append(temp);
            }

            // Return the hexadecimal string.
            return(sBuilder.ToString());
        }
Пример #30
0
 public static byte[] ComputeHash(byte[] data)
 {
     if (MD5.md5 == null)
     {
         MD5.md5 = System.Security.Cryptography.MD5.Create();
     }
     return(MD5.md5.ComputeHash(data));
 }
Пример #31
0
 public override void AppendData(byte[] data, int offset, int count)
 {
     if (_md5 == null)
     {
         _md5 = MD5.Create();
     }
     _md5.TransformBlock(data, offset, count, null, 0);
 }
		public HMACSSLv3Verify(byte[] key)
		{
			this.HashSizeValue = 288;
			this.KeyValue = (byte[]) key.Clone();
			
			_md5 = new MD5CryptoServiceProvider();
			_sha1 = new SHA1CryptoServiceProvider();
		}
Пример #33
0
 public static string MD5(string toCryString)
 {
     toCryString = toCryString ?? string.Empty;
     using (System.Security.Cryptography.MD5 provider = System.Security.Cryptography.MD5.Create())
     {
         return(BitConverter.ToString(provider.ComputeHash(Encoding.UTF8.GetBytes(toCryString))).Replace("-", "").ToLower());
     }
 }
 public WriterWorkItem(FileStream stream, BinaryWriter writer, MD5 md5)
 {
     Stream = stream;
     Writer = writer;
     Buffer = new MemoryStream(2048);
     BufferWriter = new BinaryWriter(Buffer);
     MD5 = md5;
 }
Пример #35
0
 public Program()
 {
     md5Hasher = MD5.Create();
     InitializeComponent();
     folderSelector = new FolderBrowserDialog ();
     //Could help improve time from open to use?  Nah.
     //folderSelector.RootFolder = Environment.CurrentDirectory;
 }
Пример #36
0
		/// <summary>
		/// Rfc 2104.
		/// </summary>
		/// <param name="rgbKey"></param>
		public HMACMD5 (byte[] rgbKey) 
		{
			HashSizeValue = 128;
			// Create the hash algorithms.
			hash1 = MD5.Create();
			hash2 = MD5.Create();

			this.Key = rgbKey;
		}    
Пример #37
0
 public WriterWorkItem(FileStream fileStream, UnmanagedMemoryStream memStream, MD5 md5)
 {
     _fileStream = fileStream;
     _memStream = memStream;
     _workingStream = (Stream)fileStream ?? memStream;
     Buffer = new MemoryStream(8192);
     BufferWriter = new BinaryWriter(Buffer);
     MD5 = md5;
 }
Пример #38
0
        /// <summary>
        /// Frees an object for generating the hashes that was acquired from <see cref="GetHasher"/>,
        /// adding it back to the pool for later reuse.
        /// </summary>
        /// <param name="hasher">The object to free.</param>
        static void FreeHasher(MD5 hasher)
        {
            lock (_hashersSync)
            {
                if (log.IsDebugEnabled)
                    log.DebugFormat("Freeing hasher [object hash: {0}].", hasher.GetHashCode());

                _hashers.Push(hasher);
            }
        }
        public static byte[] CreateMD5Checksum(this Stream stream, bool startAtBeginning = true, MD5 md5 = null)
        {
            if (md5 == null)
                md5 = MD5.Create();

            if (startAtBeginning)
                stream.Seek(0, SeekOrigin.Begin);

            return md5.ComputeHash(stream);
        }
		public void FixtureSetUp () 
		{
			Assembly a = Assembly.GetExecutingAssembly ();
			hashEvidence = new Hash (a);

			md5 = MD5.Create ();
			digestMd5 = hashEvidence.GenerateHash (md5);

			sha1 = SHA1.Create ();
			digestSha1 = hashEvidence.GenerateHash (sha1);
		}
Пример #41
0
 public override byte[] GetHashAndReset()
 {
     if (_md5 == null)
     {
         _md5 = MD5.Create();
     }
     _md5.TransformFinalBlock(__emptyByteArray, 0, 0);
     var hash = _md5.Hash;
     _md5.Dispose();
     _md5 = null;
     return hash;
 }
Пример #42
0
 public static string GetMD5Hash(FileInfo fileInfo)
 {
     if(MD5Crypto == null)
     {
         MD5Crypto = MD5.Create();
     }
     using (FileStream fs = fileInfo.OpenRead())
     {
         byte[] output = MD5Crypto.ComputeHash(fs);
         string hashString = Convert.ToBase64String(output);
         return hashString;
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="MD5HashStream"/> class.
        /// </summary>
        /// <param name="stream">Stream object.</param>
        /// <param name="lastTransferOffset">Offset of the transferred bytes.</param>
        /// <param name="md5hashCheck">Whether need to calculate MD5Hash.</param>
        public MD5HashStream(
            Stream stream,
            long lastTransferOffset,
            bool md5hashCheck)
        {
            this.stream = stream;
            this.md5hashOffset = lastTransferOffset;

            if ((0 == this.md5hashOffset)
                || (!md5hashCheck))
            {
                this.finishedSeparateMd5Calculator = true;
                this.succeededSeparateMd5Calculator = true;
            }
            else
            {
                this.semaphore = new SemaphoreSlim(1, 1);
            }

            if (md5hashCheck)
            {
                if (CloudStorageAccount.UseV1MD5)
                {
                    this.md5hash = new MD5CryptoServiceProvider();
                }
                else
                {
                    this.md5hash = new NativeMD5();
                }
            }

            if ((!this.finishedSeparateMd5Calculator)
                && (!this.stream.CanRead))
            {
                throw new NotSupportedException(string.Format(
                    CultureInfo.CurrentCulture,
                    Resources.StreamMustSupportReadException,
                    "Stream"));
            }

            if (!this.stream.CanSeek)
            {
                throw new NotSupportedException(string.Format(
                    CultureInfo.CurrentCulture,
                    Resources.StreamMustSupportSeekException,
                    "Stream"));
            }
        }
Пример #44
0
        public static void ContinuousHashFor(MD5 md5, Stream s, int startPosition, long count)
        {
            Ensure.NotNull(md5, "md5");
            Ensure.Nonnegative(count, "count");

            if (s.Position != startPosition)
                s.Position = startPosition;

            var buffer = new byte[4096];
            long toRead = count;
            while (toRead > 0)
            {
                int read = s.Read(buffer, 0, (int)Math.Min(toRead, buffer.Length));
                if (read == 0)
                    break;

                md5.TransformBlock(buffer, 0, read, null, 0);
                toRead -= read;
            }
        }
Пример #45
0
 //clientServer: true if random bytes should be processed as first the client bytes, then the server bytes
 //              false otherwise
 public Ssl3DeriveBytes(byte[] secret, byte[] clientRandom, byte[] serverRandom, bool clientServer)
 {
     if (secret == null || clientRandom == null || serverRandom == null)
         throw new ArgumentNullException();
     if (clientRandom.Length != 32 || serverRandom.Length != 32)
         throw new ArgumentException();
     m_Disposed = false;
     m_Secret = (byte[])secret.Clone();
     m_Random = new byte[64];
     if (clientServer) {
         Array.Copy(clientRandom, 0, m_Random, 0, 32);
         Array.Copy(serverRandom, 0, m_Random, 32, 32);
     } else {
         Array.Copy(serverRandom, 0, m_Random, 0, 32);
         Array.Copy(clientRandom, 0, m_Random, 32, 32);
     }
     m_MD5 = new MD5CryptoServiceProvider();
     m_SHA1 = new SHA1CryptoServiceProvider();
     Reset();
 }
        // constructors
        public GridFSForwardOnlyDownloadStream(
            GridFSBucket bucket,
            IReadBinding binding,
            GridFSFilesCollectionDocument filesCollectionDocument,
            bool checkMD5)
            : base(bucket, binding, filesCollectionDocument)
        {
            _checkMD5 = checkMD5;
            if (_checkMD5)
            {
                _md5 = MD5.Create();
            }

            _lastChunkNumber = (int)((filesCollectionDocument.Length - 1) / filesCollectionDocument.ChunkSizeBytes);
            _lastChunkSize = (int)(filesCollectionDocument.Length % filesCollectionDocument.ChunkSizeBytes);

            if (_lastChunkSize == 0)
            {
                _lastChunkSize = filesCollectionDocument.ChunkSizeBytes;
            }
        }
        // constructors
        public GridFSForwardOnlyUploadStream(
            GridFSBucket bucket,
            IWriteBinding binding,
            ObjectId id,
            string filename,
            BsonDocument metadata,
            IEnumerable<string> aliases,
            string contentType,
            int chunkSizeBytes,
            int batchSize)
        {
            _bucket = bucket;
            _binding = binding;
            _id = id;
            _filename = filename;
            _metadata = metadata; // can be null
            _aliases = aliases == null ? null : aliases.ToList(); // can be null
            _contentType = contentType; // can be null
            _chunkSizeBytes = chunkSizeBytes;
            _batchSize = batchSize;

            _batch = new List<byte[]>();
            _md5 = MD5.Create();
        }
Пример #48
0
 public Md5HashService()
 {
     _hasher = new MD5CryptoServiceProvider();
 }
Пример #49
0
 public MD5Proxy()
 {
     _md5 = MD5.Create();
 }
            protected override void Dispose(bool disposing)
            {
                if (this.hashProvider != null)
                {
                    this.hashProvider.Dispose();
                    this.hashProvider = null;
                }

                base.Dispose(disposing);
            }
Пример #51
0
 internal ByteStore(PRStream str)
 {
     md5 = new MD5CryptoServiceProvider();
     ByteBuffer bb = new ByteBuffer();
     int level = 100;
     SerObject(str, level, bb);
     this.b = bb.ToByteArray();
     md5 = null;
 }
        public int ReadStreamEnd()
        {
            int exitCode = StopChildProcess();

            if (md5 != null) {
                md5.TransformFinalBlock(new byte[0], 0, 0);
                mMD5SumOfPcm = md5.Hash;
                md5.Dispose();
                md5 = null;
                mMD5TmpBuffer = null;
            }

            mBytesPerFrame = 0;

            return exitCode;
        }
            public DownloadStream(Stream streamVal, bool decompressVal, byte[] hashValue)
            {
                this.stream = streamVal;
                this.decompress = decompressVal;
                this.expectedHashValue = hashValue;

                if (hashValue != null && hashValue.Length == 16)
                {
                    this.expectedHashValue = hashValue;
                    this.hashProvider = MD5Util.TryCreateMD5Provider();
                }
            }
        public void ReadStreamAbort()
        {
            System.Diagnostics.Debug.Assert(null != mChildProcess);
            mPipeServerStream.Close();
            mPipeServerStream = null;

            mChildProcess.Close();
            mChildProcess = null;

            mBinaryReader.Close();
            mBinaryReader = null;

            if (md5 != null) {
                md5.Dispose();
                md5 = null;
                mMD5TmpBuffer = null;
            }
        }
        /// <summary>
        /// FLACファイルからPCMデータを取り出し開始。
        /// </summary>
        /// <param name="flacFilePath">読み込むファイルパス。</param>
        /// <param name="skipFrames">ファイルの先頭からのスキップするフレーム数。0以外の値を指定するとMD5のチェックが行われなくなる。</param>
        /// <param name="wantFrames">取得するフレーム数。</param>
        /// <param name="pcmData">出てきたデコード後のPCMデータ。</param>
        /// <returns>0: 成功。負: 失敗。</returns>
        public int ReadStreamBegin(string flacFilePath, long skipFrames, long wantFrames, int typicalReadFrames, out PcmDataLib.PcmData pcmData_return)
        {
            List<FlacCuesheetTrackInfo> cti;
            int rv = ReadStartCommon(ReadMode.HeadereAndData, flacFilePath, skipFrames, wantFrames, out pcmData_return, out cti);
            if (rv != 0) {
                StopChildProcess();
                mBytesPerFrame = 0;
                return rv;
            }

            mBytesPerFrame = pcmData_return.BitsPerFrame / 8;

            if (CalcMD5 && skipFrames == 0 && wantFrames == mNumFrames) {
                md5 = new MD5CryptoServiceProvider();
                mMD5SumOfPcm = new byte[MD5_BYTES];
                mMD5TmpBuffer = new byte[mBytesPerFrame * typicalReadFrames];
            }

            return 0;
        }
  protected AbstractIDMigrator() {
	md5Digest = MD5.Create();	
  }
Пример #57
0
		public MD5 GetChecksumAlgorithm ()
		{
			return md5 ?? (md5 = MD5.Create ());
		}
Пример #58
0
		public void SetUp ()
		{
			md5 = new MD5Cng ();
		}
Пример #59
0
 private void WriteHeader(MD5 md5, Stream stream, ChunkHeader chunkHeader)
 {
     var chunkHeaderBytes = chunkHeader.AsByteArray();
     md5.TransformBlock(chunkHeaderBytes, 0, ChunkHeader.Size, null, 0);
     stream.Write(chunkHeaderBytes, 0, ChunkHeader.Size);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ParallelUpload"/> class.
 /// </summary>
 /// <param name="source">The source stream.</param>
 /// <param name="options">The request options.</param>
 /// <param name="blockSize">The block size to use.</param>
 /// <param name="blob">The blob to upload to.</param>
 internal ParallelUpload(Stream source, BlobRequestOptions options, long blockSize, CloudBlockBlob blob)
 {
     this.sourceStream = source;
     this.blockSize = blockSize;
     this.options = options;
     this.dispensizedStreamSize = 0;
     this.blob = blob;
     this.blobHash = MD5.Create();
     this.blockList = new List<string>();
     this.parellelism = this.GetParallelismFactor();
 }