KeyedHashAlgorithm Klass
Definition
Viktigt
En del information gäller för förhandsversionen av en produkt och kan komma att ändras avsevärt innan produkten blir allmänt tillgänglig. Microsoft lämnar inga garantier, uttryckliga eller underförstådda, avseende informationen som visas här.
Representerar den abstrakta klass från vilken alla implementeringar av nyckelade hash-algoritmer måste härledas.
public ref class KeyedHashAlgorithm abstract : System::Security::Cryptography::HashAlgorithm
public abstract class KeyedHashAlgorithm : System.Security.Cryptography.HashAlgorithm
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class KeyedHashAlgorithm : System.Security.Cryptography.HashAlgorithm
type KeyedHashAlgorithm = class
inherit HashAlgorithm
[<System.Runtime.InteropServices.ComVisible(true)>]
type KeyedHashAlgorithm = class
inherit HashAlgorithm
Public MustInherit Class KeyedHashAlgorithm
Inherits HashAlgorithm
- Arv
- Härledda
- Attribut
Exempel
Följande kodexempel visar hur du härleder från KeyedHashAlgorithm klassen.
using System;
using System.Security.Cryptography;
public class TestHMACMD5
{
static private void PrintByteArray(Byte[] arr)
{
int i;
Console.WriteLine("Length: " + arr.Length);
for (i = 0; i < arr.Length; i++)
{
Console.Write("{0:X}", arr[i]);
Console.Write(" ");
if ((i + 9) % 8 == 0) Console.WriteLine();
}
if (i % 8 != 0) Console.WriteLine();
}
public static void Main()
{
// Create a key.
byte[] key1 = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b };
// Pass the key to the constructor of the HMACMD5 class.
HMACMD5 hmac1 = new HMACMD5(key1);
// Create another key.
byte[] key2 = System.Text.Encoding.ASCII.GetBytes("KeyString");
// Pass the key to the constructor of the HMACMD5 class.
HMACMD5 hmac2 = new HMACMD5(key2);
// Encode a string into a byte array, create a hash of the array,
// and print the hash to the screen.
byte[] data1 = System.Text.Encoding.ASCII.GetBytes("Hi There");
PrintByteArray(hmac1.ComputeHash(data1));
// Encode a string into a byte array, create a hash of the array,
// and print the hash to the screen.
byte[] data2 = System.Text.Encoding.ASCII.GetBytes("This data will be hashed.");
PrintByteArray(hmac2.ComputeHash(data2));
}
}
public class HMACMD5 : KeyedHashAlgorithm
{
private MD5 hash1;
private MD5 hash2;
private bool bHashing = false;
private byte[] rgbInner = new byte[64];
private byte[] rgbOuter = new byte[64];
public HMACMD5(byte[] rgbKey)
{
HashSizeValue = 128;
// Create the hash algorithms.
hash1 = MD5.Create();
hash2 = MD5.Create();
// Get the key.
if (rgbKey.Length > 64)
{
KeyValue = hash1.ComputeHash(rgbKey);
// No need to call Initialize; ComputeHash does it automatically.
}
else
{
KeyValue = (byte[])rgbKey.Clone();
}
// Compute rgbInner and rgbOuter.
int i = 0;
for (i = 0; i < 64; i++)
{
rgbInner[i] = 0x36;
rgbOuter[i] = 0x5C;
}
for (i = 0; i < KeyValue.Length; i++)
{
rgbInner[i] ^= KeyValue[i];
rgbOuter[i] ^= KeyValue[i];
}
}
public override byte[] Key
{
get { return (byte[])KeyValue.Clone(); }
set
{
if (bHashing)
{
throw new Exception("Cannot change key during hash operation");
}
if (value.Length > 64)
{
KeyValue = hash1.ComputeHash(value);
// No need to call Initialize; ComputeHash does it automatically.
}
else
{
KeyValue = (byte[])value.Clone();
}
// Compute rgbInner and rgbOuter.
int i = 0;
for (i = 0; i < 64; i++)
{
rgbInner[i] = 0x36;
rgbOuter[i] = 0x5C;
}
for (i = 0; i < KeyValue.Length; i++)
{
rgbInner[i] ^= KeyValue[i];
rgbOuter[i] ^= KeyValue[i];
}
}
}
public override void Initialize()
{
hash1.Initialize();
hash2.Initialize();
bHashing = false;
}
protected override void HashCore(byte[] rgb, int ib, int cb)
{
if (!bHashing)
{
hash1.TransformBlock(rgbInner, 0, 64, rgbInner, 0);
bHashing = true;
}
hash1.TransformBlock(rgb, ib, cb, rgb, ib);
}
protected override byte[] HashFinal()
{
if (!bHashing)
{
hash1.TransformBlock(rgbInner, 0, 64, rgbInner, 0);
bHashing = true;
}
// Finalize the original hash.
hash1.TransformFinalBlock(new byte[0], 0, 0);
// Write the outer array.
hash2.TransformBlock(rgbOuter, 0, 64, rgbOuter, 0);
// Write the inner hash and finalize the hash.
hash2.TransformFinalBlock(hash1.Hash, 0, hash1.Hash.Length);
bHashing = false;
return hash2.Hash;
}
}
Imports System.Security.Cryptography
_
Public Class TestHMACMD5
Private Shared Sub PrintByteArray(ByVal arr() As [Byte])
Dim i As Integer
Console.WriteLine(("Length: " + arr.Length.ToString()))
For i = 0 To arr.Length - 1
Console.Write("{0:X}", arr(i))
Console.Write(" ")
If (i + 9) Mod 8 = 0 Then
Console.WriteLine()
End If
Next i
If i Mod 8 <> 0 Then
Console.WriteLine()
End If
End Sub
Public Shared Sub Main()
' Create a key.
Dim key1 As Byte() = {&HB, &HB, &HB, &HB, &HB, &HB, &HB, &HB, &HB, &HB, &HB, &HB, &HB, &HB, &HB, &HB}
' Pass the key to the constructor of the HMACMD5 class.
Dim hmac1 As New HMACMD5(key1)
' Create another key.
Dim key2 As Byte() = System.Text.Encoding.ASCII.GetBytes("KeyString")
' Pass the key to the constructor of the HMACMD5 class.
Dim hmac2 As New HMACMD5(key2)
' Encode a string into a byte array, create a hash of the array,
' and print the hash to the screen.
Dim data1 As Byte() = System.Text.Encoding.ASCII.GetBytes("Hi There")
PrintByteArray(hmac1.ComputeHash(data1))
' Encode a string into a byte array, create a hash of the array,
' and print the hash to the screen.
Dim data2 As Byte() = System.Text.Encoding.ASCII.GetBytes("This data will be hashed.")
PrintByteArray(hmac2.ComputeHash(data2))
End Sub
End Class
_
Public Class HMACMD5
Inherits KeyedHashAlgorithm
Private hash1 As MD5
Private hash2 As MD5
Private bHashing As Boolean = False
Private rgbInner(64) As Byte
Private rgbOuter(64) As Byte
Public Sub New(ByVal rgbKey() As Byte)
HashSizeValue = 128
' Create the hash algorithms.
hash1 = MD5.Create()
hash2 = MD5.Create()
' Get the key.
If rgbKey.Length > 64 Then
KeyValue = hash1.ComputeHash(rgbKey)
' No need to call Initialize; ComputeHash does it automatically.
Else
KeyValue = CType(rgbKey.Clone(), Byte())
End If
' Compute rgbInner and rgbOuter.
Dim i As Integer = 0
For i = 0 To 63
rgbInner(i) = &H36
rgbOuter(i) = &H5C
Next i
i = 0
For i = 0 To KeyValue.Length - 1
rgbInner(i) = rgbInner(i) Xor KeyValue(i)
rgbOuter(i) = rgbOuter(i) Xor KeyValue(i)
Next i
End Sub
Public Overrides Property Key() As Byte()
Get
Return CType(KeyValue.Clone(), Byte())
End Get
Set(ByVal Value As Byte())
If bHashing Then
Throw New Exception("Cannot change key during hash operation")
End If
If value.Length > 64 Then
KeyValue = hash1.ComputeHash(value)
' No need to call Initialize; ComputeHash does it automatically.
Else
KeyValue = CType(value.Clone(), Byte())
End If
' Compute rgbInner and rgbOuter.
Dim i As Integer = 0
For i = 0 To 63
rgbInner(i) = &H36
rgbOuter(i) = &H5C
Next i
For i = 0 To KeyValue.Length - 1
rgbInner(i) ^= KeyValue(i)
rgbOuter(i) ^= KeyValue(i)
Next i
End Set
End Property
Public Overrides Sub Initialize()
hash1.Initialize()
hash2.Initialize()
bHashing = False
End Sub
Protected Overrides Sub HashCore(ByVal rgb() As Byte, ByVal ib As Integer, ByVal cb As Integer)
If bHashing = False Then
hash1.TransformBlock(rgbInner, 0, 64, rgbInner, 0)
bHashing = True
End If
hash1.TransformBlock(rgb, ib, cb, rgb, ib)
End Sub
Protected Overrides Function HashFinal() As Byte()
If bHashing = False Then
hash1.TransformBlock(rgbInner, 0, 64, rgbInner, 0)
bHashing = True
End If
' Finalize the original hash.
hash1.TransformFinalBlock(New Byte(0) {}, 0, 0)
' Write the outer array.
hash2.TransformBlock(rgbOuter, 0, 64, rgbOuter, 0)
' Write the inner hash and finalize the hash.
hash2.TransformFinalBlock(hash1.Hash, 0, hash1.Hash.Length)
bHashing = False
Return hash2.Hash
End Function
End Class
Kommentarer
Hash-funktioner mappar binära strängar med godtycklig längd till små binära strängar med fast längd. En kryptografisk hash-funktion har egenskapen att det är beräkningsmässigt omöjligt att hitta två distinkta indata som hash till samma värde. Små ändringar i data resulterar i stora, oförutsägbara ändringar i hashen.
En nyckelbaserad hash-algoritm är en nyckelberoende, enkelriktad hash-funktion som används som en kod för meddelandeautentisering. Endast någon som känner till nyckeln kan verifiera hashen. Nyckelade hash-algoritmer ger autenticitet utan sekretess.
Hash-funktioner används ofta med digitala signaturer och för dataintegritet. Klassen HMACSHA1 är ett exempel på en nyckelad hash-algoritm.
På grund av kollisionsproblem med SHA-1 rekommenderar Microsoft en säkerhetsmodell baserad på SHA-256 eller bättre.
Konstruktorer
| Name | Description |
|---|---|
| KeyedHashAlgorithm() |
Initierar en ny instans av KeyedHashAlgorithm klassen. |
Fält
| Name | Description |
|---|---|
| HashSizeValue |
Representerar storleken, i bitar, på den beräknade hashkoden. (Ärvd från HashAlgorithm) |
| HashValue |
Representerar värdet för den beräknade hashkoden. (Ärvd från HashAlgorithm) |
| KeyValue |
Nyckeln som ska användas i hash-algoritmen. |
| State |
Representerar tillståndet för hash-beräkningen. (Ärvd från HashAlgorithm) |
Egenskaper
| Name | Description |
|---|---|
| CanReuseTransform |
Hämtar ett värde som anger om den aktuella transformeringen kan återanvändas. (Ärvd från HashAlgorithm) |
| CanTransformMultipleBlocks |
När det åsidosättas i en härledd klass får du ett värde som anger om flera block kan transformeras. (Ärvd från HashAlgorithm) |
| Hash |
Hämtar värdet för den beräknade hashkoden. (Ärvd från HashAlgorithm) |
| HashSize |
Hämtar storleken, i bitar, på den beräknade hashkoden. (Ärvd från HashAlgorithm) |
| InputBlockSize |
När det åsidosättas i en härledd klass hämtar indatablockstorleken. (Ärvd från HashAlgorithm) |
| Key |
Hämtar eller ställer in nyckeln som ska användas i hash-algoritmen. |
| OutputBlockSize |
När det åsidosättas i en härledd klass hämtar du utdatablockets storlek. (Ärvd från HashAlgorithm) |
Metoder
| Name | Description |
|---|---|
| Clear() |
Släpper alla resurser som används av HashAlgorithm klassen. (Ärvd från HashAlgorithm) |
| ComputeHash(Byte[], Int32, Int32) |
Beräknar hash-värdet för den angivna regionen för den angivna bytematrisen. (Ärvd från HashAlgorithm) |
| ComputeHash(Byte[]) |
Beräknar hash-värdet för den angivna bytematrisen. (Ärvd från HashAlgorithm) |
| ComputeHash(Stream) |
Beräknar hash-värdet för det angivna Stream objektet. (Ärvd från HashAlgorithm) |
| ComputeHashAsync(Stream, CancellationToken) |
Beräknar hash-värdet för det angivna Stream objektet asynkront. (Ärvd från HashAlgorithm) |
| Create() |
Föråldrad.
Föråldrad.
Skapar en instans av standardimplementeringen av en nyckelad hash-algoritm. |
| Create(String) |
Föråldrad.
Skapar en instans av den angivna implementeringen av en nyckelad hash-algoritm. |
| Dispose() |
Släpper alla resurser som används av den aktuella instansen HashAlgorithm av klassen. (Ärvd från HashAlgorithm) |
| Dispose(Boolean) |
Släpper de ohanterade resurser som används av KeyedHashAlgorithm och släpper eventuellt de hanterade resurserna. |
| Equals(Object) |
Avgör om det angivna objektet är lika med det aktuella objektet. (Ärvd från Object) |
| Finalize() |
Den här medlemmen åsidosätter Finalize(), och mer fullständig dokumentation kan vara tillgänglig i det ämnet. Tillåter ett Object försök att frigöra resurser och utföra andra rensningsåtgärder innan Object den frigörs av skräpinsamlingen. |
| GetHashCode() |
Fungerar som standard-hash-funktion. (Ärvd från Object) |
| GetType() |
Hämtar den aktuella instansen Type . (Ärvd från Object) |
| HashCore(Byte[], Int32, Int32) |
När de åsidosätts i en härledd klass dirigeras data som skrivits till objektet till hash-algoritmen för att beräkna hashen. (Ärvd från HashAlgorithm) |
| HashCore(ReadOnlySpan<Byte>) |
Dirigerar data som skrivs till objektet till hash-algoritmen för att beräkna hashen. (Ärvd från HashAlgorithm) |
| HashFinal() |
När den åsidosättas i en härledd klass slutför du hash-beräkningen efter att de senaste data har bearbetats av den kryptografiska hash-algoritmen. (Ärvd från HashAlgorithm) |
| Initialize() |
Återställer hash-algoritmen till dess ursprungliga tillstånd. (Ärvd från HashAlgorithm) |
| MemberwiseClone() |
Skapar en ytlig kopia av den aktuella Object. (Ärvd från Object) |
| ToString() |
Returnerar en sträng som representerar det aktuella objektet. (Ärvd från Object) |
| TransformBlock(Byte[], Int32, Int32, Byte[], Int32) |
Beräknar hash-värdet för den angivna regionen för indatabytematrisen och kopierar den angivna regionen för indatabytematrisen till den angivna regionen för utdatabytematrisen. (Ärvd från HashAlgorithm) |
| TransformFinalBlock(Byte[], Int32, Int32) |
Beräknar hash-värdet för den angivna regionen för den angivna bytematrisen. (Ärvd från HashAlgorithm) |
| TryComputeHash(ReadOnlySpan<Byte>, Span<Byte>, Int32) |
Försöker beräkna hash-värdet för den angivna bytematrisen. (Ärvd från HashAlgorithm) |
| TryHashFinal(Span<Byte>, Int32) |
Försök att slutföra hash-beräkningen när de senaste data bearbetas av hash-algoritmen. (Ärvd från HashAlgorithm) |
Explicita gränssnittsimplementeringar
| Name | Description |
|---|---|
| IDisposable.Dispose() |
Släpper de ohanterade resurser som används av HashAlgorithm och släpper eventuellt de hanterade resurserna. (Ärvd från HashAlgorithm) |