HashAlgorithm.ComputeHash Méthode

Définition

Calcule la valeur de hachage pour les données d'entrée.

Surcharges

ComputeHash(Byte[])

Calcule la valeur de hachage pour le tableau d'octets spécifié.

ComputeHash(Stream)

Calcule la valeur de hachage pour l'objet Stream spécifié.

ComputeHash(Byte[], Int32, Int32)

Calcule la valeur de hachage pour la région spécifiée du tableau d'octets spécifié.

ComputeHash(Byte[])

Source:
HashAlgorithm.cs
Source:
HashAlgorithm.cs
Source:
HashAlgorithm.cs

Calcule la valeur de hachage pour le tableau d'octets spécifié.

C#
public byte[] ComputeHash (byte[] buffer);

Paramètres

buffer
Byte[]

Entrée pour laquelle le code de hachage doit être calculé.

Retours

Byte[]

Code de hachage calculé.

Exceptions

buffer a la valeur null.

L'objet a déjà été supprimé.

Exemples

L’exemple suivant calcule la SHA256 valeur de hachage d’une chaîne et retourne le hachage sous la forme d’une chaîne au format hexadécimal de 64 caractères. La chaîne de hachage créée par cet exemple de code est compatible avec toute fonction de hachage SHA256 (sur n’importe quelle plateforme) qui crée une chaîne de hachage au format hexadécimal de 64 caractères.

C#
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.

S’applique à

.NET 9 et autres versions
Produit Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1

ComputeHash(Stream)

Source:
HashAlgorithm.cs
Source:
HashAlgorithm.cs
Source:
HashAlgorithm.cs

Calcule la valeur de hachage pour l'objet Stream spécifié.

C#
public byte[] ComputeHash (System.IO.Stream inputStream);

Paramètres

inputStream
Stream

Entrée pour laquelle le code de hachage doit être calculé.

Retours

Byte[]

Code de hachage calculé.

Exceptions

L'objet a déjà été supprimé.

Exemples

L’exemple suivant calcule le SHA256 hachage de tous les fichiers d’un répertoire.

C#
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)
                {
                    using (FileStream fileStream = fInfo.Open(FileMode.Open))
                    {
                        try
                        {
                            // Create a fileStream for the file.
                            // 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);
                        }
                        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();
    }
}

S’applique à

.NET 9 et autres versions
Produit Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1

ComputeHash(Byte[], Int32, Int32)

Source:
HashAlgorithm.cs
Source:
HashAlgorithm.cs
Source:
HashAlgorithm.cs

Calcule la valeur de hachage pour la région spécifiée du tableau d'octets spécifié.

C#
public byte[] ComputeHash (byte[] buffer, int offset, int count);

Paramètres

buffer
Byte[]

Entrée pour laquelle le code de hachage doit être calculé.

offset
Int32

Offset dans le tableau d'octets à partir duquel l'utilisation de données commence.

count
Int32

Nombre d'octets dans le tableau à utiliser comme données.

Retours

Byte[]

Code de hachage calculé.

Exceptions

count n’est pas une valeur valide.

- ou -

buffer a une longueur non valide.

buffer a la valeur null.

offset est hors limites. Ce paramètre requiert un nombre non négatif.

L'objet a déjà été supprimé.

S’applique à

.NET 9 et autres versions
Produit Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1