简体   繁体   English

c# hash 和 php MD5 文件/文件夹 Z0800FC577294C34E04528AD2839Z 不同

[英]c# hash and php MD5 file/folder hash not the same

I have to MD5 hash files/folders on both a client(C#) and a server(PHP) file structure.我必须在客户端(C#)和服务器(PHP)文件结构上使用 MD5 hash 文件/文件夹。 (Server land is PHP and client land is c#.) The problem is while they work they do not match. (服务器区是 PHP,客户端区是 c#。)问题是它们工作时不匹配。 Any ideas would be greatly appreciated任何想法将不胜感激

Here are my two algorithms这是我的两个算法

C# C#

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace nofolder
{
    public class classHasher
    {
        /**********
         *  recursive folder MD5 hash of a dir
         */
        MD5 hashAlgo = null;
        StringBuilder sb;
        public classHasher()
        {
            hashAlgo = new MD5CryptoServiceProvider();
        }
        public string getHash(String path)
        {
            // get the file attributes for file or directory
            if (File.Exists(path)) return getHashOverFile(path);
            if (Directory.Exists(path)) return getHashOverFolder(path);
            return "";
        }
        public string getHashOverFolder(String path)
        {
            sb = new StringBuilder();
            getFolderContents(path);
            return sb.ToString().GetHashCode().ToString();
        }
        public string getHashOverFile(String filename)
        {
            sb = new StringBuilder();
            getFileHash(filename);
            return sb.ToString().GetHashCode().ToString();
        }
        private void getFolderContents(string fold)
        {
            foreach (var d in Directory.GetDirectories(fold))
            {
                getFolderContents(d);
            }
            foreach (var f in Directory.GetFiles(fold))
            {
                getFileHash(f);
            }
        }
        private void getFileHash(String f)
        {
            using (FileStream file = new FileStream(f, FileMode.Open, FileAccess.Read))
            {
                byte[] retVal = hashAlgo.ComputeHash(file);
                file.Close();
                foreach (var y in retVal)
                {
                    sb.Append(y.ToString());
                }
            }
        }
    }
}

PHP PHP

function include__md5_dir($dir){
    /**********
    *   recursive folder MD5 hash of a dir
    */
    if (!is_dir($dir)){
        return  md5_file($dir);
    }

    $filemd5s = array();
    $d = dir($dir);

    while (false !== ($entry = $d->read())){
        if ($entry != '.' && $entry != '..'){
             if (is_dir($dir.'/'.$entry)){
                 $filemd5s[] = include__md5_dir($dir.'/'.$entry);
             }
             else{
                 $filemd5s[] = md5_file($dir.'/'.$entry);
             }
         }
    }
    $d->close();
    return md5(implode('', $filemd5s));
}

EDIT.编辑。

I have decided the c# must change .我已经决定c# 必须改变 the PHP is fine as it is . PHP 很好 The first code that works 100% gets the bounty第一个 100% 有效的代码获得赏金

Your PHP code is assembling hexadecimal numbers (as per the md5_file() documentation) 您的PHP代码正在组装十六进制数字(根据md5_file()文档)

Your C# code is assembling non-0-padded decimal numbers. 您的C#代码正在组装非0填充的十进制数字。
You need to y.ToString("x2") to format as hexadecimal. 您需要y.ToString("x2")格式化为十六进制。

Also, return sb.ToString().GetHashCode().ToString(); 另外, return sb.ToString().GetHashCode().ToString(); is extremely wrong. 是非常错误的。 Don't call GetHashCode() ; 不要调用GetHashCode() ; it's not what you want. 这不是你想要的。

I eventually fixed this myself and I include the answer for future posterity - the key to this solution was irradicating the different default dir ORDERING that linux and windows use . 我最终自己解决了这个问题,并为以后的解决提供了答案- 该解决方案的关键是阐明Linux和Windows使用的不同默认目录ORDERING This was only tested on the linux server (Cent OS6.3) and Windows 7 Client. 仅在linux服务器(Cent OS6.3)和Windows 7客户端上对此进行了测试。

C# C#

public class classHasher
    {
        /**********
        *   recursive folder MD5 hash of a dir
        */
        MD5 hashAlgo = null;
        StringBuilder sb;
        public classHasher()
        {
            hashAlgo = new MD5CryptoServiceProvider();
        }

        public string UltraHasher(String path)
        { 
            /**********
            *   recursive folder MD5 hash of a dir
            */
            if (!Directory.Exists(path))
            {
                return  getHashOverFile(path);
            }

            List<string> filemd5s = new List<string>();
            List<string> dir = new List<string>();

            if (Directory.GetDirectories(path) != null) foreach (var d in Directory.GetDirectories(path))
            {
                dir.Add(d);

            }
            if (Directory.GetFiles(path) != null) foreach (var f in Directory.GetFiles(path))
            {
                dir.Add(f);                
            }

            dir.Sort();

            foreach (string entry in dir)
            {
                if (Directory.Exists(entry))
                {
                    string rtn = UltraHasher(entry.ToString());
                    //Debug.WriteLine("   ULTRRAAHASHER:! " + entry.ToString() + ":" + rtn);
                    filemd5s.Add(rtn); 
                } 
                if (File.Exists(entry))
                {
                    string rtn = getHashOverFile(entry.ToString());
                    //Debug.WriteLine("   FILEEEEHASHER:! " + entry.ToString() + ":" + rtn);
                    filemd5s.Add(rtn);
                }
            }

            //Debug.WriteLine("   ULTRRAASUMMMM:! " + String.Join("", filemd5s.ToArray()));
            string tosend = CalculateMD5Hash(String.Join("", filemd5s.ToArray()));
            //Debug.WriteLine("   YEAHHAHHAHHAH:! " + tosend);
            return tosend;
        }

        public string getHashOverFile(String filename)
        {
            sb = new StringBuilder();
            getFileHash(filename);
            return sb.ToString();
        }
        private void getFileHash(String f)
        {
            using (FileStream file = new FileStream(f, FileMode.Open, FileAccess.Read))
            {
                byte[] retVal = hashAlgo.ComputeHash(file);
                file.Close();
                foreach (var y in retVal)
                {
                    sb.Append(y.ToString("x2"));
                }
            }
        }
        public string CalculateMD5Hash(string input)
        {
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hash = hashAlgo.ComputeHash(inputBytes);

            StringBuilder sz = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sz.Append(hash[i].ToString("x2"));
            }
            return sz.ToString();
        }
 }

PHP 的PHP

function md5_dir($dir){
        /**********
        *   recursive folder MD5 hash of a dir
        */
        if (!is_dir($dir)){
            return  md5_file($dir);
        }

        $filemd5s = array();
        $bit = array();
        $d = scandir($dir);

        foreach($d as $entry){
            if ($entry != '.' && $entry != '..'){
                 $bit[] = $entry;
            }
        }

        asort($bit);

        foreach($bit as $entry){
            if (is_dir($dir.'/'.$entry)){
                $sz = md5_dir($dir.'/'.$entry);
                //echo "\n   ULTRRAAHASHER:! ".$dir.'/'.$entry.":$sz";
                $filemd5s[] = $sz;
             }
             else{
                $sz = md5_file($dir.'/'.$entry);
                $filemd5s[] = $sz;
                //echo "\n   FILEEEEHASHER:! ".$dir.'/'.$entry.":$sz";
             }
         }
        //echo "\n   ULTRRAASUMMMM:! ".implode('', $filemd5s)."";
        //echo "\n   YEAHHAHHAHHAH:! ".md5(implode('', $filemd5s))."";
        return md5(implode('', $filemd5s));
    }

these two will traverse either a C# Windows and or a PHP linux folder and return the SAME hashes for all dirs (recursive, so it includes sub dirs) inside Linuxland and all inside Windowsland. 这两个将遍历C#Windows和PHP linux文件夹,并为Linuxland和Windowsland内部的所有目录返回递归的SAME散列(递归,因此它包括子目录)。

For sort like C# asort() is case sensitive so you will need per example natcasesort()对于像 C# 这样的排序, asort() 区分大小写,因此您需要每个示例 natcasesort()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM