Csharp/CSharp Tutorial/Security/SHA1Managed

Материал из .Net Framework эксперт
Версия от 15:17, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Generate the hash code of the file"s contents

<source lang="csharp">using System; using System.IO; using System.Security.Cryptography; class MainClass {

   public static void Main(string[] args)
   {
       using (HashAlgorithm hashAlg = new SHA1Managed())
       {
           using (Stream file = new FileStream("C:\\test.txt", FileMode.Open, FileAccess.Read))
           {
               byte[] hash = hashAlg.ruputeHash(file);
               // Display the hash code of the file to the console.
               Console.WriteLine(BitConverter.ToString(hash));
           }
       }
   }

}</source>

Generate the hash code of the password

<source lang="csharp">using System; using System.Text; using System.Security.Cryptography; class MainClass {

   public static void Main(string[] args)
   {
       HashAlgorithm hashAlg = new SHA1Managed();
       using (hashAlg)
       {
           byte[] pwordData = Encoding.Default.GetBytes("password");
           byte[] hash = hashAlg.ruputeHash(pwordData);
           Console.WriteLine(BitConverter.ToString(hash));
       }
   }

}</source>

5B-AA-61-E4-C9-B9-3F-3F-06-82-25-0B-6C-F8-33-1B-7E-E6-8F-D8

Produce a SHA1 hash

<source lang="csharp">using System; using System.Security.Cryptography;

 class Class1
 {
   static void Main(string[] args)
   {
     string dataToHash = "this is a test";
     string key = "ABCDEFGHIJKLMNOPQRSTUVWX";
     byte[] dataToHash_Bytes = System.Text.Encoding.Unicode.GetBytes( dataToHash );
     byte[] key_Bytes = System.Text.Encoding.ASCII.GetBytes( key );
     MACTripleDES mac = new MACTripleDES( key_Bytes );
     
     byte[] result_Bytes = mac.ruputeHash( dataToHash_Bytes );
     Console.WriteLine( System.Text.Encoding.ASCII.GetString( result_Bytes ));
     SHA1Managed sha1 = new SHA1Managed();
     byte[] sha1_Bytes = sha1.ruputeHash( dataToHash_Bytes);
     Console.WriteLine( System.Text.Encoding.ASCII.GetString( sha1_Bytes ));
   }
 }</source>