HashAlgorithm.ComputeHash HashAlgorithm.ComputeHash HashAlgorithm.ComputeHash HashAlgorithm.ComputeHash Method

Definicja

Oblicza wartość skrótu dla danych wejściowych.Computes the hash value for the input data.

Przeciążenia

ComputeHash(Byte[]) ComputeHash(Byte[]) ComputeHash(Byte[]) ComputeHash(Byte[])

Oblicza wartość skrótu dla określonej tablicy bajtów.Computes the hash value for the specified byte array.

ComputeHash(Stream) ComputeHash(Stream) ComputeHash(Stream) ComputeHash(Stream)

Oblicza wartość skrótu dla określonego Stream obiektu.Computes the hash value for the specified Stream object.

ComputeHash(Byte[], Int32, Int32) ComputeHash(Byte[], Int32, Int32) ComputeHash(Byte[], Int32, Int32) ComputeHash(Byte[], Int32, Int32)

Oblicza wartość skrótu dla określonego regionu określonej tablicy bajtów.Computes the hash value for the specified region of the specified byte array.

ComputeHash(Byte[]) ComputeHash(Byte[]) ComputeHash(Byte[]) ComputeHash(Byte[])

Oblicza wartość skrótu dla określonej tablicy bajtów.Computes the hash value for the specified byte array.

public:
 cli::array <System::Byte> ^ ComputeHash(cli::array <System::Byte> ^ buffer);
public byte[] ComputeHash (byte[] buffer);
member this.ComputeHash : byte[] -> byte[]
Public Function ComputeHash (buffer As Byte()) As Byte()

Parametry

buffer
Byte[]

Dane wejściowe do obliczenia kodu skrótu dla.The input to compute the hash code for.

Zwraca

Byte[]

Obliczony kod skrótu.The computed hash code.

Wyjątki

Obiekt został już usunięty.The object has already been disposed.

Przykłady

Poniższy przykład oblicza SHA256 wartość skrótu ciągu i zwraca skrót jako 64-znakowy ciąg szesnastkowy.The following example computes the SHA256 hash value of a string and returns the hash as a 64-character, hexadecimal-formatted string. Ciąg skrótu utworzony przez ten przykład kodu jest zgodny z dowolnymi funkcjami skrótu SHA256 (na dowolnej platformie), które tworzą 64-znakowy ciąg skrótu w formacie szesnastkowym.The hash string created by this code example is compatible with any SHA256 hash function (on any platform) that creates a 64-character, hexadecimal-formatted hash string.

using System;
using System.Security.Cryptography;
using System.Text;

public class Program
{
    public static void Main()
    {
        string source = "Hello World!";
        using (SHA256 sha256Hash = SHA256.Create())
        {
            string hash = GetHash(sha256Hash, source);

            Console.WriteLine($"The SHA256 hash of {source} is: {hash}.");

            Console.WriteLine("Verifying the hash...");

            if (VerifyHash(sha256Hash, source, hash))
            {
                Console.WriteLine("The hashes are the same.");
            }
            else
            {
                Console.WriteLine("The hashes are not same.");
            }
        }
    }

    private static string GetHash(HashAlgorithm hashAlgorithm, string input)
    {

        // Convert the input string to a byte array and compute the hash.
        byte[] data = hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(input));

        // Create a new Stringbuilder to collect the bytes
        // and create a string.
        var 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.
    private static bool VerifyHash(HashAlgorithm hashAlgorithm, string input, string hash)
    {
        // Hash the input.
        var hashOfInput = GetHash(hashAlgorithm, input);

        // Create a StringComparer an compare the hashes.
        StringComparer comparer = StringComparer.OrdinalIgnoreCase;

        return comparer.Compare(hashOfInput, hash) == 0;
    }

}
// The example displays the following output:
//    The SHA256 hash of Hello World! is: 7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069.
//    Verifying the hash...
//    The hashes are the same.
Imports System.Security.Cryptography
Imports System.Text

Public Module Program
    Public Sub Main()
        Dim source As String = "Hello World!"
        Using sha256Hash As SHA256 = SHA256.Create()

            Dim hash As String = GetHash(sha256Hash, source)

            Console.WriteLine($"The SHA256 hash of {source} is: {hash}.")

            Console.WriteLine("Verifying the hash...")

            If VerifyHash(sha256Hash, source, hash) Then
                Console.WriteLine("The hashes are the same.")
            Else
                Console.WriteLine("The hashes are not same.")
            End If
        End Using
    End Sub 

    Private Function GetHash(ByVal hashAlgorithm As HashAlgorithm, ByVal input As String) As String

        ' Convert the input string to a byte array and compute the hash.
        Dim data As Byte() = hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(input))

        ' Create a new Stringbuilder to collect the bytes
        ' and create a string.
        Dim sBuilder As New StringBuilder()

        ' Loop through each byte of the hashed data 
        ' and format each one as a hexadecimal string.
        For i As Integer = 0 To data.Length - 1
            sBuilder.Append(data(i).ToString("x2"))
        Next

        ' Return the hexadecimal string.
        Return sBuilder.ToString()
    End Function

    ' Verify a hash against a string.
    Private Function VerifyHash(hashAlgorithm As HashAlgorithm, input As String, hash As String) As Boolean
        ' Hash the input.
        Dim hashOfInput As String = GetHash(hashAlgorithm, input)

        ' Create a StringComparer an compare the hashes.
        Dim comparer As StringComparer = StringComparer.OrdinalIgnoreCase

        Return comparer.Compare(hashOfInput, hash) = 0
    End Function
End Module
' The example displays the following output:
'    The SHA256 hash of Hello World! is: 7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069.
'    Verifying the hash...
'    The hashes are the same.

ComputeHash(Stream) ComputeHash(Stream) ComputeHash(Stream) ComputeHash(Stream)

Oblicza wartość skrótu dla określonego Stream obiektu.Computes the hash value for the specified Stream object.

public:
 cli::array <System::Byte> ^ ComputeHash(System::IO::Stream ^ inputStream);
public byte[] ComputeHash (System.IO.Stream inputStream);
member this.ComputeHash : System.IO.Stream -> byte[]
Public Function ComputeHash (inputStream As Stream) As Byte()

Parametry

inputStream
Stream Stream Stream Stream

Dane wejściowe do obliczenia kodu skrótu dla.The input to compute the hash code for.

Zwraca

Byte[]

Obliczony kod skrótu.The computed hash code.

Wyjątki

Obiekt został już usunięty.The object has already been disposed.

Przykłady

Poniższy przykład oblicza SHA256 wartość skrótu dla wszystkich plików w katalogu.The following example calculates the SHA256 hash for all files in a directory.

using System;
using System.IO;
using System.Security.Cryptography;

public class HashDirectory
{
    public static void Main(String[] args)
    {
        if (args.Length < 1)
        {
            Console.WriteLine("No directory selected.");
            return;
        }

        string directory = args[0];
        if (Directory.Exists(directory))
        {
            // Create a DirectoryInfo object representing the specified directory.
           var dir = new DirectoryInfo(directory);
            // Get the FileInfo objects for every file in the directory.
            FileInfo[] files = dir.GetFiles();
            // Initialize a SHA256 hash object.
            using (SHA256 mySHA256 = SHA256.Create())
            {
                // Compute and print the hash values for each file in directory.
                foreach (FileInfo fInfo in files)
                {
                    try { 
                        // Create a fileStream for the file.
                        FileStream fileStream = fInfo.Open(FileMode.Open);
                        // Be sure it's positioned to the beginning of the stream.
                        fileStream.Position = 0;
                        // Compute the hash of the fileStream.
                        byte[] hashValue = mySHA256.ComputeHash(fileStream);
                        // Write the name and hash value of the file to the console.
                        Console.Write($"{fInfo.Name}: ");
                        PrintByteArray(hashValue);
                        // Close the file.
                        fileStream.Close();
                    }
                    catch (IOException e) {
                        Console.WriteLine($"I/O Exception: {e.Message}");
                    }
                    catch (UnauthorizedAccessException e) {
                        Console.WriteLine($"Access Exception: {e.Message}");
                    }
                }
            }
        }
        else
        {
            Console.WriteLine("The directory specified could not be found.");
        }
    }

    // Display the byte array in a readable format.
    public static void PrintByteArray(byte[] array)
    {
        for (int i = 0; i < array.Length; i++)
        {
            Console.Write($"{array[i]:X2}");
            if ((i % 4) == 3) Console.Write(" ");
        }
        Console.WriteLine();
    }
}
Imports System.IO
Imports System.Security.Cryptography

Public Module HashDirectory

    Public Sub Main(ByVal args() As String)
        If args.Length < 1 Then
            Console.WriteLine("No directory selected")
            Return
        End If

        Dim targetDirectory As String = args(0)
        If Directory.Exists(targetDirectory) Then
            ' Create a DirectoryInfo object representing the specified directory.
            Dim dir As New DirectoryInfo(targetDirectory)
            ' Get the FileInfo objects for every file in the directory.
            Dim files As FileInfo() = dir.GetFiles()
            ' Initialize a SHA256 hash object.
            Using mySHA256 As SHA256 = SHA256.Create()
                ' Compute and print the hash values for each file in directory.
                For Each fInfo  As FileInfo In files
                    Try
                        ' Create a fileStream for the file.
                        Dim fileStream = fInfo.Open(FileMode.Open)
                        ' Be sure it's positioned to the beginning of the stream.
                        fileStream.Position = 0
                        ' Compute the hash of the fileStream.
                        Dim hashValue() As Byte = mySHA256.ComputeHash(fileStream)
                        ' Write the name of the file to the Console.
                        Console.Write(fInfo.Name + ": ")
                        ' Write the hash value to the Console.
                        PrintByteArray(hashValue)
                        ' Close the file.
                        fileStream.Close()
                    Catch e As IOException
                        Console.WriteLine($"I/O Exception: {e.Message}")
                    Catch e As UnauthorizedAccessException 
                        Console.WriteLine($"Access Exception: {e.Message}")
                    End Try    
                Next 
            End Using
        Else
           Console.WriteLine("The directory specified could not be found.")
        End If
    End Sub

    ' Print the byte array in a readable format.
    Public Sub PrintByteArray(array() As Byte)
        For i As Integer = 0 To array.Length - 1
            Console.Write($"{array(i):X2}")
            If i Mod 4 = 3 Then
                Console.Write(" ")
            End If
        Next 
        Console.WriteLine()

    End Sub 
End Module

ComputeHash(Byte[], Int32, Int32) ComputeHash(Byte[], Int32, Int32) ComputeHash(Byte[], Int32, Int32) ComputeHash(Byte[], Int32, Int32)

Oblicza wartość skrótu dla określonego regionu określonej tablicy bajtów.Computes the hash value for the specified region of the specified byte array.

public:
 cli::array <System::Byte> ^ ComputeHash(cli::array <System::Byte> ^ buffer, int offset, int count);
public byte[] ComputeHash (byte[] buffer, int offset, int count);
member this.ComputeHash : byte[] * int * int -> byte[]
Public Function ComputeHash (buffer As Byte(), offset As Integer, count As Integer) As Byte()

Parametry

buffer
Byte[]

Dane wejściowe do obliczenia kodu skrótu dla.The input to compute the hash code for.

offset
Int32 Int32 Int32 Int32

Przesunięcie do tablicy bajtów, z której ma zacząć korzystać z danych.The offset into the byte array from which to begin using data.

count
Int32 Int32 Int32 Int32

Liczba bajtów w tablicy, które mają być używane jako dane.The number of bytes in the array to use as data.

Zwraca

Byte[]

Obliczony kod skrótu.The computed hash code.

Wyjątki

countjest nieprawidłową wartością.count is an invalid value.

—lub—-or- bufferNieprawidłowa długość.buffer length is invalid.

offsetjest poza zakresem.offset is out of range. Ten parametr wymaga liczby nieujemnej.This parameter requires a non-negative number.

Obiekt został już usunięty.The object has already been disposed.

Dotyczy