MD5CryptoServiceProvider MD5CryptoServiceProvider MD5CryptoServiceProvider MD5CryptoServiceProvider Class

定义

使用加密服务提供程序 (CSP) 提供的实现,计算输入数据的 MD5 哈希值。Computes the MD5 hash value for the input data using the implementation provided by the cryptographic service provider (CSP). 此类不能被继承。This class cannot be inherited.

public ref class MD5CryptoServiceProvider sealed : System::Security::Cryptography::MD5
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class MD5CryptoServiceProvider : System.Security.Cryptography.MD5
type MD5CryptoServiceProvider = class
    inherit MD5
Public NotInheritable Class MD5CryptoServiceProvider
Inherits MD5
继承
MD5CryptoServiceProviderMD5CryptoServiceProviderMD5CryptoServiceProviderMD5CryptoServiceProvider
属性

示例

下面的代码示例计算MD5哈希值data并将其返回。The following code example computes the MD5 hash value for data and returns it.

private:
   array<Byte>^ MD5hash( array<Byte>^data )
   {
      // This is one implementation of the abstract class MD5.
      MD5^ md5 = gcnew MD5CryptoServiceProvider;

      array<Byte>^ result = md5->ComputeHash( data );

      return result;
   }
byte[] MD5hash (byte[] data)
 {
    // This is one implementation of the abstract class MD5.
    MD5 md5 = new MD5CryptoServiceProvider();

    byte[] result = md5.ComputeHash(data);

    return result;
 }
Function MD5hash(data() As Byte) As Byte()
    ' This is one implementation of the abstract class MD5.
    Dim md5 As New MD5CryptoServiceProvider()
       
    Dim result As Byte() = md5.ComputeHash(data)
       
    Return result
End Function

下面的代码示例计算MD5哈希值的字符串,并返回为 32 个字符的十六进制格式的字符串的哈希。The following code example computes the MD5 hash value of a string and returns the hash as a 32-character, hexadecimal-formatted string. 此代码示例所创建的哈希字符串适用于任何 MD5 哈希函数 (在任何平台上) 上创建 32 个字符的十六进制格式的哈希字符串。The hash string created by this code example is compatible with any MD5 hash function (on any platform) that creates a 32-character, hexadecimal-formatted hash string.

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

class Example
{
    // Hash an input string and return the hash as
    // a 32 character hexadecimal string.
    static string getMd5Hash(string input)
    {
        // Create a new instance of the MD5CryptoServiceProvider object.
        MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();

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

        // Create a new Stringbuilder to collect the bytes
        // and create a string.
        StringBuilder 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.
    static bool verifyMd5Hash(string input, string hash)
    {
        // Hash the input.
        string hashOfInput = getMd5Hash(input);

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

        if (0 == comparer.Compare(hashOfInput, hash))
        {
            return true;
        }
        else
        {
            return false;
        }
    }


    static void Main()
    {
        string source = "Hello World!";
        
        string hash = getMd5Hash(source);

        Console.WriteLine("The MD5 hash of " + source + " is: " + hash + ".");

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

        if (verifyMd5Hash(source, hash))
        {
            Console.WriteLine("The hashes are the same.");
        }
        else
        {
            Console.WriteLine("The hashes are not same.");
        }
        
    }
}
// This code example produces the following output:
//
// The MD5 hash of Hello World! is: ed076287532e86365e841e92bfc50d8c.
// Verifying the hash...
// The hashes are the same.
Imports System
Imports System.Security.Cryptography
Imports System.Text

Module Example

    ' Hash an input string and return the hash as
    ' a 32 character hexadecimal string.
    Function getMd5Hash(ByVal input As String) As String
        ' Create a new instance of the MD5CryptoServiceProvider object.
        Dim md5Hasher As New MD5CryptoServiceProvider()

        ' Convert the input string to a byte array and compute the hash.
        Dim data As Byte() = md5Hasher.ComputeHash(Encoding.Default.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.
        Dim i As Integer
        For i = 0 To data.Length - 1
            sBuilder.Append(data(i).ToString("x2"))
        Next i

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

    End Function


    ' Verify a hash against a string.
    Function verifyMd5Hash(ByVal input As String, ByVal hash As String) As Boolean
        ' Hash the input.
        Dim hashOfInput As String = getMd5Hash(input)

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

        If 0 = comparer.Compare(hashOfInput, hash) Then
            Return True
        Else
            Return False
        End If

    End Function



    Sub Main()
        Dim source As String = "Hello World!"

        Dim hash As String = getMd5Hash(source)

        Console.WriteLine("The MD5 hash of " + source + " is: " + hash + ".")

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

        If verifyMd5Hash(source, hash) Then
            Console.WriteLine("The hashes are the same.")
        Else
            Console.WriteLine("The hashes are not same.")
        End If

    End Sub
End Module
' This code example produces the following output:
'
' The MD5 hash of Hello World! is: ed076287532e86365e841e92bfc50d8c.
' Verifying the hash...
' The hashes are the same.

注解

哈希函数的二进制字符串映射到固定长度的小型二进制字符串的任意长度。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; that is, hashes of two sets of data should match if the corresponding data also matches. 中的哈希大,无法预测更改的数据结果的小改动。Small changes to the data result in large, unpredictable changes in the hash.

备注

安全哈希算法 SHA-256 和 SHA-512 等较新的哈希函数均可用。Newer hash functions such as the Secure Hash Algorithms SHA-256 and SHA-512 are available. 请考虑使用SHA256类或SHA512类而不是MD5CryptoServiceProvider类。Consider using the SHA256 class or the SHA512 class instead of the MD5CryptoServiceProvider class. 使用MD5CryptoServiceProvider仅为与旧版应用程序和数据兼容。Use MD5CryptoServiceProvider only for compatibility with legacy applications and data.

哈希大小MD5CryptoServiceProvider类是 128 位。The hash size for the MD5CryptoServiceProvider class is 128 bits.

ComputeHash方法的MD5CryptoServiceProvider类 16 个字节数组形式返回的哈希。The ComputeHash methods of the MD5CryptoServiceProvider class return the hash as an array of 16 bytes. 请注意,某些 MD5 实现产生 32 个字符的十六进制格式的哈希。Note that some MD5 implementations produce a 32-character, hexadecimal-formatted hash. 若要与此类实现进行互操作,设置格式的返回值ComputeHash为十六进制值的方法。To interoperate with such implementations, format the return value of the ComputeHash methods as a hexadecimal value.

构造函数

MD5CryptoServiceProvider() MD5CryptoServiceProvider() MD5CryptoServiceProvider() MD5CryptoServiceProvider()

初始化 MD5CryptoServiceProvider 类的新实例。Initializes a new instance of the MD5CryptoServiceProvider class.

方法

Clear() Clear() Clear() Clear()

释放 HashAlgorithm 类使用的所有资源。Releases all resources used by the HashAlgorithm class.

(Inherited from HashAlgorithm)
ComputeHash(Byte[]) ComputeHash(Byte[]) ComputeHash(Byte[]) ComputeHash(Byte[])

计算指定字节数组的哈希值。Computes the hash value for the specified byte array.

(Inherited from HashAlgorithm)
ComputeHash(Byte[], Int32, Int32) ComputeHash(Byte[], Int32, Int32) ComputeHash(Byte[], Int32, Int32) ComputeHash(Byte[], Int32, Int32)

计算指定字节数组的指定区域的哈希值。Computes the hash value for the specified region of the specified byte array.

(Inherited from HashAlgorithm)
ComputeHash(Stream) ComputeHash(Stream) ComputeHash(Stream) ComputeHash(Stream)

计算指定 Stream 对象的哈希值。Computes the hash value for the specified Stream object.

(Inherited from HashAlgorithm)
Dispose() Dispose() Dispose() Dispose()

释放 HashAlgorithm 类的当前实例所使用的所有资源。Releases all resources used by the current instance of the HashAlgorithm class.

(Inherited from HashAlgorithm)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

释放由 HashAlgorithm 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the HashAlgorithm and optionally releases the managed resources.

(Inherited from HashAlgorithm)
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize() Finalize() Finalize() Finalize()
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
HashCore(Byte[], Int32, Int32) HashCore(Byte[], Int32, Int32) HashCore(Byte[], Int32, Int32) HashCore(Byte[], Int32, Int32)

当在派生类中重写时,将写入对象的数据路由到哈希算法以计算哈希值。When overridden in a derived class, routes data written to the object into the hash algorithm for computing the hash.

(Inherited from HashAlgorithm)
HashCore(ReadOnlySpan<Byte>) HashCore(ReadOnlySpan<Byte>) HashCore(ReadOnlySpan<Byte>) HashCore(ReadOnlySpan<Byte>) Inherited from HashAlgorithm
HashFinal() HashFinal() HashFinal() HashFinal()

当在派生类中重写时,在加密流对象处理完最后的数据后完成哈希计算。When overridden in a derived class, finalizes the hash computation after the last data is processed by the cryptographic stream object.

(Inherited from HashAlgorithm)
Initialize() Initialize() Initialize() Initialize()

初始化 MD5CryptoServiceProvider 的实例。Initializes an instance of MD5CryptoServiceProvider.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)
TransformBlock(Byte[], Int32, Int32, Byte[], Int32) TransformBlock(Byte[], Int32, Int32, Byte[], Int32) TransformBlock(Byte[], Int32, Int32, Byte[], Int32) 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.

(Inherited from HashAlgorithm)
TransformFinalBlock(Byte[], Int32, Int32) TransformFinalBlock(Byte[], Int32, Int32) TransformFinalBlock(Byte[], Int32, Int32) TransformFinalBlock(Byte[], Int32, Int32)

计算指定字节数组的指定区域的哈希值。Computes the hash value for the specified region of the specified byte array.

(Inherited from HashAlgorithm)
TryComputeHash(ReadOnlySpan<Byte>, Span<Byte>, Int32) TryComputeHash(ReadOnlySpan<Byte>, Span<Byte>, Int32) TryComputeHash(ReadOnlySpan<Byte>, Span<Byte>, Int32) TryComputeHash(ReadOnlySpan<Byte>, Span<Byte>, Int32) Inherited from HashAlgorithm
TryHashFinal(Span<Byte>, Int32) TryHashFinal(Span<Byte>, Int32) TryHashFinal(Span<Byte>, Int32) TryHashFinal(Span<Byte>, Int32) Inherited from HashAlgorithm

属性

CanReuseTransform CanReuseTransform CanReuseTransform CanReuseTransform

获取一个值,该值指示是否可重复使用当前转换。Gets a value indicating whether the current transform can be reused.

(Inherited from HashAlgorithm)
CanTransformMultipleBlocks CanTransformMultipleBlocks CanTransformMultipleBlocks CanTransformMultipleBlocks

当在派生类中重写时,获取一个值,该值指示是否可以转换多个块。When overridden in a derived class, gets a value indicating whether multiple blocks can be transformed.

(Inherited from HashAlgorithm)
Hash Hash Hash Hash

获取计算所得的哈希代码的值。Gets the value of the computed hash code.

(Inherited from HashAlgorithm)
HashSize HashSize HashSize HashSize

获取计算所得的哈希代码的大小(以位为单位)。Gets the size, in bits, of the computed hash code.

(Inherited from HashAlgorithm)
InputBlockSize InputBlockSize InputBlockSize InputBlockSize

当在派生类中重写时,获取输入块的大小。When overridden in a derived class, gets the input block size.

(Inherited from HashAlgorithm)
OutputBlockSize OutputBlockSize OutputBlockSize OutputBlockSize

当在派生类中重写时,获取输出块的大小。When overridden in a derived class, gets the output block size.

(Inherited from HashAlgorithm)

字段

HashSizeValue HashSizeValue HashSizeValue HashSizeValue

表示计算所得的哈希代码的大小(以位为单位)。Represents the size, in bits, of the computed hash code.

(Inherited from HashAlgorithm)
HashValue HashValue HashValue HashValue

表示计算所得的哈希代码的值。Represents the value of the computed hash code.

(Inherited from HashAlgorithm)
State State State State

表示哈希计算的状态。Represents the state of the hash computation.

(Inherited from HashAlgorithm)

显式界面实现

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

释放由 HashAlgorithm 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the HashAlgorithm and optionally releases the managed resources.

(Inherited from HashAlgorithm)

适用于

另请参阅