Compute and Verify Hash Value Using C#

ฟังก์ชันสำหรับคำนวนค่า Hash ของไฟล์ โดยสนับสนุนอัลกอริทึ่ม MD5, SHA-1, SHA-256, SHA-384, SHA-512

public static string ComputeMD5Hash(string fileName)
{
            return ComputeHash(fileName, new MD5CryptoServiceProvider());
}

public static string ComputeSHA1Hash(string fileName)
{
            return ComputeHash(fileName, new SHA1Managed());
}

public static string ComputeSHA256Hash(string fileName)
{
            return ComputeHash(fileName, new SHA256Managed());
}

public static string ComputeSHA384Hash(string fileName)
{
            return ComputeHash(fileName, new SHA384Managed());
}

public static string ComputeSHA512Hash(string fileName)
{
            return ComputeHash(fileName, new SHA512Managed());
}

public static string ComputeHash(string fileName, HashAlgorithm hashAlgorithm)
{
            FileStream stmcheck = File.OpenRead(fileName);
            try
            {
                        byte[] hash = hashAlgorithm.ComputeHash(stmcheck);
                        string computed = BitConverter.ToString(hash).Replace(“-”, “”);
                        return computed;
            }
            finally
            {
                        stmcheck.Close();
            }
}

public static bool VerifyHash(string fileName,
string hashAlgorithm,
string hashValue)
{
            string expectedHashString = “”;
            // Make sure that hashing algorithm name is specified.
            if (hashAlgorithm == null)
            {
                        hashAlgorithm = “”;
            }

            // Size of hash is based on the specified algorithm.
            switch (hashAlgorithm.ToUpper())
            {
                        case “SHA1″:
                                    // Compute a new hash string to compare.
                                    expectedHashString = ComputeSHA1Hash(fileName);
                        break;

                        case “SHA256″:
                                    // Compute a new hash string to compare.
                                    expectedHashString = ComputeSHA256Hash(fileName);
                        break;

                        case “SHA384″:
                                    // Compute a new hash string to compare.
                                    expectedHashString = ComputeSHA384Hash(fileName);
                        break;

                        case “SHA512″:
                                    // Compute a new hash string to compare.
                                    expectedHashString = ComputeSHA512Hash(fileName);
                        break;

                        default: // Must be MD5
                                    expectedHashString = ComputeMD5Hash(fileName);
                        break;
            }

            // If the computed hash matches the specified hash,
            // the plain text value must be correct.
            return (hashValue == expectedHashString);
}

No comments yet

Leave a reply