KeyedHashAlgorithm Класс
Определение
Представляет абстрактный класс, из которого создаются все реализации хэш-алгоритмов с ключом.Represents the abstract class from which all implementations of keyed hash algorithms must derive.
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
- Наследование
- Производный
- Атрибуты
Примеры
В следующем примере кода показано, как выполнить наследование от KeyedHashAlgorithm класса.The following code example demonstrates how to derive from the KeyedHashAlgorithm class.
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 == false)
{
hash1.TransformBlock(rgbInner, 0, 64, rgbInner, 0);
bHashing = true;
}
hash1.TransformBlock(rgb, ib, cb, rgb, ib);
}
protected override byte[] HashFinal()
{
if (bHashing == false)
{
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
Комментарии
Хэш-функции сопоставляют двоичные строки произвольной длины с маленькими двоичными строками фиксированной длины.Hash functions map binary strings of an arbitrary length to small binary strings of a fixed length. Функция криптографической хэш-функции имеет свойство, которое вычисляется нецелесообразно для поиска двух различных входных значений, которые являются хэш-значениями для одного и того же значения.A cryptographic hash function has the property that it is computationally infeasible to find two distinct inputs that hash to the same value. Небольшие изменения данных приводят к большим непредсказуемым изменениям в хэш-коде.Small changes to the data result in large, unpredictable changes in the hash.
Хэш-алгоритм с ключом — это зависящая от ключа односторонняя хэш-функция, используемая в качестве кода проверки подлинности сообщения.A keyed hash algorithm is a key-dependent, one-way hash function used as a message authentication code. Только тот, кто знает ключ, может проверить хэш.Only someone who knows the key can verify the hash. Алгоритмы хэширования с ключом обеспечивают подлинность без безопасной передачи.Keyed hash algorithms provide authenticity without secrecy.
Хэш-функции обычно используются с цифровыми подписями и для обеспечения целостности данных.Hash functions are commonly used with digital signatures and for data integrity. HMACSHA1Класс является примером хэш-алгоритма с ключом.The HMACSHA1 class is an example of a keyed hash algorithm.
Из-за проблем с SHA1 корпорация Майкрософт рекомендует использовать модель безопасности на основе SHA256 или более высокого уровня.Due to collision problems with SHA1, Microsoft recommends a security model based on SHA256 or better.
Конструкторы
KeyedHashAlgorithm() |
Инициализирует новый экземпляр класса KeyedHashAlgorithm.Initializes a new instance of the KeyedHashAlgorithm class. |
Поля
HashSizeValue |
Представляет размер вычисленного хэш-кода в битах.Represents the size, in bits, of the computed hash code. (Унаследовано от HashAlgorithm) |
HashValue |
Представляет значение вычисленного хэш-кода.Represents the value of the computed hash code. (Унаследовано от HashAlgorithm) |
KeyValue |
Ключ, используемый в хэш-алгоритме.The key to use in the hash algorithm. |
State |
Представляет состояние процесса вычисления хэша.Represents the state of the hash computation. (Унаследовано от HashAlgorithm) |
Свойства
CanReuseTransform |
Получает значение, указывающее на возможность повторного использования текущего преобразования.Gets a value indicating whether the current transform can be reused. (Унаследовано от HashAlgorithm) |
CanTransformMultipleBlocks |
Если переопределено в производном классе, возвращает значение, указывающее, возможно ли преобразование нескольких блоков.When overridden in a derived class, gets a value indicating whether multiple blocks can be transformed. (Унаследовано от HashAlgorithm) |
Hash |
Получает значение вычисленного хэш-кода.Gets the value of the computed hash code. (Унаследовано от HashAlgorithm) |
HashSize |
Получает размер вычисленного хэш-кода в битах.Gets the size, in bits, of the computed hash code. (Унаследовано от HashAlgorithm) |
InputBlockSize |
При переопределении в производном классе получает размер входного блока.When overridden in a derived class, gets the input block size. (Унаследовано от HashAlgorithm) |
Key |
Получает или задает ключ, используемый в хэш-алгоритме.Gets or sets the key to use in the hash algorithm. |
OutputBlockSize |
При переопределении в производном классе получает размер выходного блока.When overridden in a derived class, gets the output block size. (Унаследовано от HashAlgorithm) |
Методы
Clear() |
Освобождает все ресурсы, используемые классом HashAlgorithm.Releases all resources used by the HashAlgorithm class. (Унаследовано от HashAlgorithm) |
ComputeHash(Byte[]) |
Вычисляет хэш-значение для заданного массива байтов.Computes the hash value for the specified byte array. (Унаследовано от HashAlgorithm) |
ComputeHash(Byte[], Int32, Int32) |
Вычисляет хэш-значение для заданной области заданного массива байтов.Computes the hash value for the specified region of the specified byte array. (Унаследовано от HashAlgorithm) |
ComputeHash(Stream) |
Вычисляет хэш-значение для заданного объекта Stream.Computes the hash value for the specified Stream object. (Унаследовано от HashAlgorithm) |
ComputeHashAsync(Stream, CancellationToken) |
Асинхронно вычисляет хэш-значение для заданного объекта Stream.Asynchronously computes the hash value for the specified Stream object. (Унаследовано от HashAlgorithm) |
Create() |
Создает экземпляр реализации по умолчанию хэш-алгоритма с ключом.Creates an instance of the default implementation of a keyed hash algorithm. |
Create(String) |
Создает экземпляр заданной реализации хэш-алгоритма с ключом.Creates an instance of the specified implementation of a keyed hash algorithm. |
Dispose() |
Освобождает все ресурсы, используемые текущим экземпляром класса HashAlgorithm.Releases all resources used by the current instance of the HashAlgorithm class. (Унаследовано от HashAlgorithm) |
Dispose(Boolean) |
Освобождает неуправляемые ресурсы, используемые объектом KeyedHashAlgorithm, а при необходимости освобождает также управляемые ресурсы.Releases the unmanaged resources used by the KeyedHashAlgorithm and optionally releases the managed resources. |
Equals(Object) |
Определяет, равен ли указанный объект текущему объекту.Determines whether the specified object is equal to the current object. (Унаследовано от Object) |
Finalize() |
Этот член переопределяет Finalize(); по данной теме может быть доступна более полная документация.This member overrides Finalize(), and more complete documentation might be available in that topic. Позволяет объекту Object попытаться освободить ресурсы и выполнить другие операции очистки, перед тем как объект Object будет утилизирован в процессе сборки мусора.Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. |
GetHashCode() |
Служит хэш-функцией по умолчанию.Serves as the default hash function. (Унаследовано от Object) |
GetType() |
Возвращает объект Type для текущего экземпляра.Gets the Type of the current instance. (Унаследовано от Object) |
HashCore(Byte[], Int32, Int32) |
При переопределении в производном классе передает данные, записанные в объект, на вход хэш-алгоритма для вычисления хэша.When overridden in a derived class, routes data written to the object into the hash algorithm for computing the hash. (Унаследовано от HashAlgorithm) |
HashCore(ReadOnlySpan<Byte>) |
Передает записываемые в объект данные в хэш-алгоритм для вычисления хэша.Routes data written to the object into the hash algorithm for computing the hash. (Унаследовано от HashAlgorithm) |
HashFinal() |
Если переопределено в производном классе, завершает вычисление хэша после обработки последних данных криптографическим хэш-алгоритмом.When overridden in a derived class, finalizes the hash computation after the last data is processed by the cryptographic hash algorithm. (Унаследовано от HashAlgorithm) |
Initialize() |
Сбрасывает хэш-алгоритм в исходное состояние.Resets the hash algorithm to its initial state. (Унаследовано от HashAlgorithm) |
MemberwiseClone() |
Создает неполную копию текущего объекта Object.Creates a shallow copy of the current Object. (Унаследовано от Object) |
ToString() |
Возвращает строку, представляющую текущий объект.Returns a string that represents the current object. (Унаследовано от Object) |
TransformBlock(Byte[], Int32, Int32, Byte[], Int32) |
Вычисляет хэш-значение для заданной области входного массива байтов и копирует указанную область входного массива байтов в заданную область выходного массива байтов.Computes the hash value for the specified region of the input byte array and copies the specified region of the input byte array to the specified region of the output byte array. (Унаследовано от HashAlgorithm) |
TransformFinalBlock(Byte[], Int32, Int32) |
Вычисляет хэш-значение для заданной области заданного массива байтов.Computes the hash value for the specified region of the specified byte array. (Унаследовано от HashAlgorithm) |
TryComputeHash(ReadOnlySpan<Byte>, Span<Byte>, Int32) |
Пытается вычислить хэш-значение для заданного массива байтов.Attempts to compute the hash value for the specified byte array. (Унаследовано от HashAlgorithm) |
TryHashFinal(Span<Byte>, Int32) |
Пытается завершить вычисление хэша после обработки последних данных хэш-алгоритмом.Attempts to finalize the hash computation after the last data is processed by the hash algorithm. (Унаследовано от HashAlgorithm) |
Явные реализации интерфейса
IDisposable.Dispose() |
Освобождает неуправляемые ресурсы, используемые объектом HashAlgorithm, а при необходимости освобождает также управляемые ресурсы.Releases the unmanaged resources used by the HashAlgorithm and optionally releases the managed resources. (Унаследовано от HashAlgorithm) |