生成哈希

更新:2007 年 11 月

托管哈希类可以散列字节数组或托管流对象。下面的示例使用 SHA1 哈希算法创建字符串的哈希值。该示例使用 UnicodeEncoding 类将字符串转换为使用 SHA1Managed 类进行哈希处理的字节数组。然后将该哈希值显示到控制台。

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);
      }
   }
}

上面的代码将把下面的字符串显示到控制台:

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

请参见

概念

验证哈希

使用哈希代码确保数据完整性

其他资源

加密任务

加密服务