Csharp/C Sharp by API/System.Security.Cryptography/HashAlgorithm

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

HashAlgorithm.ComputeHash

  
using System;
using System.Text;
using System.Security.Cryptography;
class MainClass {
    public static void Main(string[] args) {
        HashAlgorithm hashAlg = null;
        hashAlg = new SHA1Managed();
        using (hashAlg) {
            byte[] pwordData = Encoding.Default.GetBytes(args[1]);
            byte[] hash = hashAlg.ruputeHash(pwordData);
            Console.WriteLine(BitConverter.ToString(hash));
        }
    }
}


HashAlgorithm.Create()

  
using System;
using System.IO;
using System.Security.Cryptography;
static class MainClass
{
    static void Main(string[] args)
    {
        // Create the hashing object.
        using (HashAlgorithm hashAlg = HashAlgorithm.Create())
        {
            using (FileStream fsA = new FileStream("c:\\test.txt", FileMode.Open),
                fsB = new FileStream("c:\\test1.txt", FileMode.Open)){
                // Calculate the hash for the files.
                byte[] hashBytesA = hashAlg.ruputeHash(fsA);
                byte[] hashBytesB = hashAlg.ruputeHash(fsB);
                // Compare the hashes.
                if (BitConverter.ToString(hashBytesA) == BitConverter.ToString(hashBytesB))
                {
                    Console.WriteLine("Files match.");
                } else {
                    Console.WriteLine("No match.");
                }
            }
        }
    }
}