【发布时间】:2014-06-10 09:09:02
【问题描述】:
我正在尝试制作一个计算两个日期的哈希值的程序。日期是文件的创建日期和上次更新的日期时间。我在每种情况下都得到相同的哈希值,即使更新日期和创建日期不同。我的简单目标是计算两个日期的哈希值并进行比较。请帮我处理我的代码。更正代码或建议任何新代码。提前致谢。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace ConsoleApplication3
{
class Program
{
static void Main()
{
string source, source1;
FileInfo info = new FileInfo("D:\\file.txt");
DateTime time1 = info.CreationTime;
Console.WriteLine(time1);
DateTime time2 = info.LastAccessTime;
Console.WriteLine(time2);
DateTime time3 = info.LastWriteTime;
Console.WriteLine(time3);
source = Convert.ToString(time1);
source1 = Convert.ToString(time3);
using (MD5 md5Hash = MD5.Create())
{
string hash = GetMd5Hash(md5Hash, source);
string hash1 = GetMd5Hash(md5Hash, source1);
Console.WriteLine("The MD5 hash of" + time1 + "is:" + hash + ".");
Console.WriteLine("The MD5 hash of" + time3 + "is:" + hash1 + ".");
if (VerifyMd5Hash(md5Hash, source, hash))
{
Console.WriteLine("The hashes are the same.");
}
else
{
Console.WriteLine("The hashes are not same.");
}
Console.ReadLine();
}
}
static string GetMd5Hash(MD5 md5Hash, string source1)
{
FileInfo info = new FileInfo("D:\\file.txt");
DateTime time3 = info.LastWriteTime;
source1 = Convert.ToString(time3);
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(source1));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// 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();
}
// Verify a hash against a string.
static bool VerifyMd5Hash(MD5 md5Hash, string source1, string hash)
{
// Hash the input.
string hashOfInput = GetMd5Hash(md5Hash, source1);
// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
if (0 == comparer.Compare(hashOfInput, hash))
{
return true;
}
else
{
return false;
}
}
}
}
【问题讨论】:
-
你有什么问题吗?你有什么问题?
-
日期一样吗?
-
散列文件内容,而不是日期。如果文件相同,日期有什么关系?