From f68bb1864b40c69d12b44db5aa33125aef39e150 Mon Sep 17 00:00:00 2001 From: marcinzelent Date: Sat, 17 Mar 2018 15:33:00 +0100 Subject: Restructuring --- .../Utilities/PasswordFileHandler.cs | 80 ++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 DistributedPasswordCracker.Server/Utilities/PasswordFileHandler.cs (limited to 'DistributedPasswordCracker.Server/Utilities') diff --git a/DistributedPasswordCracker.Server/Utilities/PasswordFileHandler.cs b/DistributedPasswordCracker.Server/Utilities/PasswordFileHandler.cs new file mode 100644 index 0000000..e4b1e76 --- /dev/null +++ b/DistributedPasswordCracker.Server/Utilities/PasswordFileHandler.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Security.Cryptography; +using DistributedPasswordCracker.Server.Models; + +namespace DistributedPasswordCracker.Server.Utilities +{ + class PasswordFileHandler + { + private static readonly Converter Converter = CharToByte; + + /// + /// With this method you can make you own password file + /// + /// Name of password file + /// List of usernames + /// List of passwords in clear text + /// if usernames and passwords have different lengths + public static void WritePasswordFile(String filename, String[] usernames, String[] passwords) + { + HashAlgorithm messageDigest = new SHA1CryptoServiceProvider(); + if (usernames.Length != passwords.Length) + { + throw new ArgumentException("usernames and passwords must be same lengths"); + } + using (FileStream fs = new FileStream(filename, FileMode.CreateNew, FileAccess.Write)) + using (StreamWriter sw = new StreamWriter(fs)) + { + for (int i = 0; i < usernames.Length; i++) + { + byte[] passwordAsBytes = Array.ConvertAll(passwords[i].ToCharArray(), GetConverter()); + byte[] encryptedPassword = messageDigest.ComputeHash(passwordAsBytes); + String line = usernames[i] + ":" + Convert.ToBase64String(encryptedPassword) + "\n"; + sw.WriteLine(line); + } + } + } + + /// + /// Reads all the username + encrypted password from the password file + /// + /// the name of the password file + /// A list of (username, encrypted password) pairs + public static List ReadPasswordFile(String filename) + { + List result = new List(); + + FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read); + using (StreamReader sr = new StreamReader(fs)) + { + + while (!sr.EndOfStream) + { + String line = sr.ReadLine(); + String[] parts = line.Split(":".ToCharArray()); + UserInfo userInfo = new UserInfo(parts[0], parts[1]); + result.Add(userInfo); + } + return result; + } + } + + public static Converter GetConverter() + { + return Converter; + } + + /// + /// Converting a char to a byte can be done in many ways. + /// This is one way ... + /// + /// + /// + private static byte CharToByte(char ch) + { + return Convert.ToByte(ch); + } + } +} \ No newline at end of file -- cgit v1.2.3