Advertisement
vovanhik_24

Task1.4

Apr 8th, 2025
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.89 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5.  
  6. namespace PasswordHashing
  7. {
  8.     class Program
  9.     {
  10.         static readonly List<string> storedHashes = new List<string>();
  11.  
  12.         static void Main(string[] args)
  13.         {
  14.             Console.Write("Введите пароль: ");
  15.             string password = Console.ReadLine();
  16.  
  17.             string hash = HashPassword(password);
  18.             storedHashes.Add(hash);
  19.  
  20.             Console.WriteLine($"Пароль: {password}");
  21.             Console.WriteLine($"Хэш: {hash}");
  22.  
  23.             Console.Write("\nВведите пароль для проверки:");
  24.             string input = Console.ReadLine();
  25.  
  26.             if (VerifyPassword(input))
  27.             {
  28.                 Console.ForegroundColor = ConsoleColor.Green;
  29.                 Console.WriteLine("Пароль верный!");
  30.             }
  31.             else
  32.             {
  33.                 Console.ForegroundColor = ConsoleColor.Red;
  34.                 Console.WriteLine("Неверный пароль!");
  35.             }
  36.  
  37.             Console.ResetColor();
  38.         }
  39.  
  40.         static string HashPassword(string password)
  41.         {
  42.             using (SHA256 sha256 = SHA256.Create())
  43.             {
  44.                 byte[] bytes = Encoding.UTF8.GetBytes(password);
  45.                 byte[] hashBytes = sha256.ComputeHash(bytes);
  46.  
  47.                 StringBuilder builder = new StringBuilder();
  48.  
  49.                 foreach (byte b in hashBytes)
  50.                 {
  51.                     builder.Append(b.ToString("x2"));
  52.                 }
  53.                
  54.                 return builder.ToString();
  55.             }
  56.         }
  57.  
  58.         static bool VerifyPassword(string inputPassword)
  59.         {
  60.             string inputHash = HashPassword(inputPassword);
  61.             return storedHashes.Contains(inputHash);
  62.         }
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement