在C#中,可以使用加密類庫(如System.Security.Cryptography)來驗證哈希數據的完整性
using System.Security.Cryptography;
public static byte[] ComputeHash(byte[] data)
{
using (SHA256 sha256 = SHA256.Create())
{
return sha256.ComputeHash(data);
}
}
public static bool CompareHashes(byte[] hash1, byte[] hash2)
{
if (hash1.Length != hash2.Length)
{
return false;
}
for (int i = 0; i < hash1.Length; i++)
{
if (hash1[i] != hash2[i])
{
return false;
}
}
return true;
}
byte[] originalData = Encoding.UTF8.GetBytes("Hello, world!");
byte[] receivedData = Encoding.UTF8.GetBytes("Hello, world!");
byte[] originalHash = ComputeHash(originalData);
byte[] receivedHash = ComputeHash(receivedData);
bool isIntegrityValid = CompareHashes(originalHash, receivedHash);
if (isIntegrityValid)
{
Console.WriteLine("數據完整性驗證成功!");
}
else
{
Console.WriteLine("數據完整性驗證失敗!");
}
請注意,這只是一個簡單的示例,實際應用中可能需要根據具體情況進行調整。例如,可以使用更安全的哈希算法(如SHA-3)或添加鹽值以提高安全性。