Calculates a small example of the string and file MD5 values

  • 2020-05-19 05:36:46
  • OfStack


// Computed string MD5 value 
        public string GetMD5(string sDataIn)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] bytValue, bytHash;
            bytValue = System.Text.Encoding.UTF8.GetBytes(sDataIn);
            bytHash = md5.ComputeHash(bytValue);
            md5.Clear();
            string sTemp = "";
            for (int i = 0; i < bytHash.Length; i++)
            {
                sTemp += bytHash[i].ToString("X").PadLeft(2, '0');
            }
            return sTemp.ToLower();
        }
        
        // Computational file MD5 value 
        public string MD5Value(String filepath)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] md5ch;
            using (FileStream fs = File.OpenRead(filepath))
            {
                md5ch = md5.ComputeHash(fs);
            }
            md5.Clear();
            string strMd5 = "";
            for (int i = 0; i < md5ch.Length - 1; i++)
            {
                strMd5 += md5ch[i].ToString("x").PadLeft(2, '0');
            }
            return strMd5;
        }


Related articles: