Generieren eines Hashs

Aktualisiert: November 2007

Mit den verwalteten Hashklassen kann entweder ein Bytearray oder ein verwaltetes Streamobjekt als Hashwert dargestellt werden. Im folgenden Beispiel wird der SHA1-Hashalgorithmus zum Erstellen eines Hashwerts für eine Zeichenfolge verwendet. Im folgenden Beispiel wird die Zeichenfolge mit der UnicodeEncoding-Klasse in ein Bytearray konvertiert, von dem mithilfe der SHA1Managed-Klasse ein Hashwert generiert wird. Der Hashwert wird anschließend in der Konsole angezeigt.

Imports System
Imports System.Security.Cryptography
Imports System.Text

Module Module1
    Sub Main()
        Dim HashValue() As Byte

        Dim MessageString As String = "This is the original message!"

        'Create a new instance of the UnicodeEncoding class to 
        'convert the string into an array of Unicode bytes.
        Dim UE As New UnicodeEncoding()

        'Convert the string into an array of bytes.
        Dim MessageBytes As Byte() = UE.GetBytes(MessageString)

        'Create a new instance of the SHA1Managed class to create 
        'the hash value.
        Dim SHhash As New SHA1Managed()

        'Create the hash value from the array of bytes.
        HashValue = SHhash.ComputeHash(MessageBytes)

        'Display the hash value to the console. 
        Dim b As Byte
        For Each b In HashValue
            Console.Write("{0} ", b)
        Next b
    End Sub
End Module
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

class Class1
{
   static void Main(string[] args)
   {
      byte[] HashValue;

      string MessageString = "This is the original message!";

      //Create a new instance of the UnicodeEncoding class to 
      //convert the string into an array of Unicode bytes.
      UnicodeEncoding UE = new UnicodeEncoding();

      //Convert the string into an array of bytes.
     byte[] MessageBytes = UE.GetBytes(MessageString);

      //Create a new instance of the SHA1Managed class to create 
      //the hash value.
      SHA1Managed SHhash = new SHA1Managed();

      //Create the hash value from the array of bytes.
      HashValue = SHhash.ComputeHash(MessageBytes);

      //Display the hash value to the console. 
      foreach(byte b in HashValue)
      {
         Console.Write("{0} ", b);
      }
   }
}

Durch diesen Code wird in der Konsole folgende Zeichenfolge angezeigt:

59 4 248 102 77 97 142 201 210 12 224 93 25 41 100 197 213 134 130 135

Siehe auch

Konzepte

Überprüfen eines Hashs

Gewährleisten der Datenintegrität über Hashcodes

Weitere Ressourcen

Kryptografische Aufgaben

Kryptografische Dienste