|
|
using System; |
|
|
using System.IO; |
|
|
using System.Security.Cryptography; |
|
|
using System.Text; |
|
|
|
|
|
namespace WpfEditor |
|
|
{ |
|
|
|
|
|
|
|
|
|
|
|
public static class MD5 |
|
|
{ |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static string ComputeHash(string input) |
|
|
{ |
|
|
if (string.IsNullOrEmpty(input)) |
|
|
return string.Empty; |
|
|
|
|
|
using (var md5 = System.Security.Cryptography.MD5.Create()) |
|
|
{ |
|
|
byte[] inputBytes = Encoding.UTF8.GetBytes(input); |
|
|
byte[] hashBytes = md5.ComputeHash(inputBytes); |
|
|
|
|
|
return BitConverter.ToString(hashBytes).Replace("-", "").ToLower(); |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static string ComputeFileHash(string filePath) |
|
|
{ |
|
|
if (!File.Exists(filePath)) |
|
|
throw new FileNotFoundException("无法找到文件", filePath); |
|
|
|
|
|
using (var md5 = System.Security.Cryptography.MD5.Create()) |
|
|
using (var stream = File.OpenRead(filePath)) |
|
|
{ |
|
|
byte[] hashBytes = md5.ComputeHash(stream); |
|
|
return BitConverter.ToString(hashBytes).Replace("-", "").ToLower(); |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static bool VerifyHash(string input, string hash) |
|
|
{ |
|
|
string computedHash = ComputeHash(input); |
|
|
return string.Equals(computedHash, hash, StringComparison.OrdinalIgnoreCase); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static bool VerifyFileHash(string filePath, string hash) |
|
|
{ |
|
|
string computedHash = ComputeFileHash(filePath); |
|
|
return string.Equals(computedHash, hash, StringComparison.OrdinalIgnoreCase); |
|
|
} |
|
|
} |
|
|
} |