我必须在客户端(C#)和服务器(PHP)文件结构上对文件/文件夹进行 MD5 哈希处理。(服务器域是 PHP,客户端域是 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
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));
}
编辑。
我已经决定c# 必须改变。PHP 很好。第一个 100% 有效的代码获得赏金