Unity中C#的MD5操作

    /// <summary>
    /// 將文件生成一個MD5
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    public static string MD5File(string file)
    {
        try
        {
            using (FileStream fs = new FileStream(file, FileMode.Open))
            {
                //System.Security.Cryptography.MD5
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(fs);

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
        }
        catch (Exception ex)
        {
            throw new Exception("md5file() fail, error:" + ex.Message);
        }
    }
    /// <summary>
    /// 計算字符串的MD5值
    /// </summary>
    public static string MD5String(String str)
    {
        if (string.IsNullOrEmpty(str))
        {
            return string.Empty;
        }

        String word = str;
        StringBuilder pwd = new StringBuilder();
        //System.Security.Cryptography.MD5
        MD5 md5 = MD5.Create();
        byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(word));
        for (int i = 0; i < s.Length; i++)
        {
            //pwd = pwd + s[i].ToString("x");
            pwd.Append(s[i].ToString("x2"));
        }
        return pwd.ToString();
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章