static void MatchMaking() { while (true) { if (connectedUsers.Count >= 2) { matchedUsers.Add(connectedUsers[0]); Console.WriteLine("Added user: {0}", connectedUsers[0]); sData = CipherUtility.Encrypt <AesManaged>("Matched", "password", "salt"); lock (msgsLock) { msgs.Add(infoSender[connectedUsers[0]], sData); } if (connectedUsers.Count >= 2) { matchedUsers.Add(connectedUsers[1]); Console.WriteLine("Added user: {0}", connectedUsers[1]); sData = CipherUtility.Encrypt <AesManaged>("Matched", "password", "salt"); lock (msgsLock) { msgs.Add(infoSender[connectedUsers[1]], sData); } gwList.Add(new GameWorld(connectedUsers[0], connectedUsers[1])); connectedUsers.RemoveRange(0, 2); } } } }
public void CreateSaltTest() { string actual; actual = CipherUtility.CreateSalt(); Assert.IsTrue(!String.IsNullOrEmpty(actual)); }
private void btnEncrypt_Click(object sender, EventArgs e) { try { var type = Type.GetType((string)this.cbxEncryptionMethod.Items[this.cbxEncryptionMethod.SelectedIndex]); var cipher = new CipherUtility((System.Security.Cryptography.SymmetricAlgorithm)Activator.CreateInstance(type)); if (this.rbString.Checked) { this.txtResult.Text = cipher.Encrypt( this.txtSource.Text, this.txtPassword.Text, this.txtSalt.Text, this.chkBase64LineBreaks.Checked ? Base64FormattingOptions.InsertLineBreaks : Base64FormattingOptions.None); } else { this.txtResult.Text = cipher.EncryptByteArray( Encoding.UTF8.GetBytes(this.txtSource.Text), this.txtPassword.Text, this.txtSalt.Text, this.chkBase64LineBreaks.Checked ? Base64FormattingOptions.InsertLineBreaks : Base64FormattingOptions.None); } } catch (Exception err) { MessageBox.Show(BOG.Framework.DetailedException.WithUserContent(ref err), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Reads in the most frequent n-grams from our training data to use for /// </summary> /// /// <returns> /// Dictionary containing the most frequent n-grams from the dataset /// </returns> /// /// <author> /// Ian Cordova - 6:50pm 4/30/2018 /// </author> static Dictionary <string, int> GetTopnGrams(int a_numberOfnGrams) { Dictionary <string, int> topnGrams = new Dictionary <string, int>(); string path = "C:\\Users\\icordova\\Source\\Repos\\CipherBreaker\\CipherTrainingData\\DataSetTriGrams.txt"; using (FileStream fs = File.Open(path, FileMode.Open)) using (BufferedStream bs = new BufferedStream(fs)) using (StreamReader sr = new StreamReader(bs)) { string line; // find specified number of nGrams for (int i = 0; i < a_numberOfnGrams / 2; ++i) { // end of file if ((line = sr.ReadLine()) == null) { break; } Tuple <string, int> nGramData = CipherUtility.ParseDataSetLine(line); topnGrams.Add(nGramData.Item1, nGramData.Item2); } } return(topnGrams); }
static void Main(string[] args) { CipherUtility cipherUtility = new CipherUtility(); Console.WriteLine("Type a string to encrypt: "); string userInput = Console.ReadLine(); Console.WriteLine("\n"); Console.Write("Enter your Key: "); int key = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("\n"); Console.WriteLine("Encrypted Data"); string cipherText = cipherUtility.Encipher(userInput, key); Console.WriteLine(cipherText); Console.Write("\n"); Console.WriteLine("Decrypted Data: "); string t = cipherUtility.Decipher(cipherText, key); Console.WriteLine(t); Console.Write("\n"); Console.ReadKey(); }
public void DecryptExceptionTest() { string text = "Teststring"; string password = string.Empty; string salt = "Teststring"; string actual; actual = CipherUtility.Decrypt <AesManaged>(text, password, salt); Assert.Fail("An Exception should have been thrown"); }
public void CipherUtilitySymmetric() { string plaintext = "IamAPl4inTextSTring!@#$%^&*()<>"; string salt = CipherUtility.GetNewSalt(); string encryptedText = CipherUtility.Encrypt(plaintext, salt); string decryptedText = CipherUtility.Decrypt(encryptedText, salt); Assert.AreEqual(plaintext, decryptedText); }
/// <summary> /// Allows user to select a txt file to be encoded using our cipher /// </summary> /// /// <returns> /// string plainText which contains the contents of the specified txt file /// </returns> /// /// <author> /// Ian Cordova - 7:25pm - 4/30/2018 /// </author> private async Task <Dictionary <string, int> > SelectTrainingDataAsync() { string dataText; // Set parameters for opening a file var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; picker.FileTypeFilter.Add(".txt"); // Open file directory to choose a txt file StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { try { dataText = await FileIO.ReadTextAsync(file, 0); } catch { dataText = "The text file that you have chosen is not utf encoded."; } } else { dataText = ""; } Dictionary <string, int> trainingBiGrams = new Dictionary <string, int>(); using (StringReader sr = new StringReader(dataText)) { string line; // read file and populate dict while ((line = sr.ReadLine()) != null) { try { Tuple <string, int> nGramData = CipherUtility.ParseDataSetLine(line); trainingBiGrams.Add(nGramData.Item1, nGramData.Item2); } catch (Exception err) { tbTrainingFile.Text = "Training data selected not in correct format!"; } } } tbTrainingFile.Text = "Loaded: " + file.Name; return(trainingBiGrams); }
/// <summary> /// Creates a connection parameter object an uses System.Guid.NewGuid() to generate a salt value. /// </summary> /// <param name="type">Connection type</param> /// <param name="name">Connection name</param> /// <param name="host">Host IP</param> /// <param name="database">Database</param> /// <param name="user">User</param> /// <param name="password">Password</param> /// <param name="port">Port</param> public ConnectionParameters(String type = "", String name = "", String host = "", String database = "", String user = "", String password = "", String port = "") { Salt = CipherUtility.CreateSalt(); Type = type; Name = name; Host = host; Database = database; User = user; Password = password; Port = port; }
public void EncryptionEmptyAesKeyTest() { String tempAeskey = CipherUtility.TemporaryAESKeyDelete(); Boolean testSuccessful = false; Assert.IsFalse(String.IsNullOrEmpty(CipherUtility.Encrypt("Teststring", "Teststting"))); testSuccessful = CipherUtility.TemporaryAESKeyRestore(tempAeskey); Assert.IsTrue(testSuccessful); }
public bool Validar_Credenciales(string name, string password) { try { password = CipherUtility.Encript(password); var usuario_logueado = db.Personal.FirstOrDefault(c => c.Nombre == name && c.Password == password); return(usuario_logueado != null ? true : false); } catch (Exception) { } return(false); }
/// <summary> /// Removes all punctuation and non-needed characters from the string. /// </summary> /// /// <param name="a_text"> string to be cleaned </param> /// /// <returns> /// Original string removed of unnecessary characters. /// </returns> /// /// <author> /// Ian Cordova - 9:00pm, 4/23/2018 /// </author> private static string CleanString(string a_text) { string cleanString = ""; foreach (char i in a_text) { if (CipherUtility.IsEnglishLetter(i) || i == ' ' || i == '\n' || i == '\r') { cleanString += i; } } return(cleanString); }
public async Task CreateAsync(AuthenticationTokenCreateContext context) { // Initilize refresh token service this._refreshTokenService = GetRefreshTokenService(new DbFactory() { }); //Get the client Id from Ticket properties var clientId = context.Ticket.Properties.Dictionary[Constant.OAuthorization_Properties_ClientId]; if (string.IsNullOrEmpty(clientId)) { return; } var userName = context.Ticket.Identity.FindFirst(ClaimTypes.NameIdentifier); if (userName == null) { return; } // Generating a Unique Refresh Token ID var refreshTokenId = Guid.NewGuid().ToString("n"); var refreshTokenLifeTime = context.OwinContext.Get <string>(Constant.OAuthorization_OAuth_ClientRefreshTokenLifeTime); // Creating the Refresh Token object var refreshToken = new RefreshToken() { // storing the refreshTokenId in hash format ID = CipherUtility.GetHash(refreshTokenId), ClientId = clientId, UserName = userName.Value, IssuedTime = DateTime.UtcNow, ExpiredTime = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime)) }; // Setting Issued and Expired time of the refresh token context.Ticket.Properties.IssuedUtc = refreshToken.IssuedTime; context.Ticket.Properties.ExpiresUtc = refreshToken.ExpiredTime; refreshToken.ProtectedTicket = context.SerializeTicket(); var result = _refreshTokenService.Add(refreshToken); if (result) { context.SetToken(refreshTokenId); } }
/// <summary> /// Scores the chromosome by adding the sum of the frequencies /// in our text * the frequencies in the data set. /// </summary> /// /// <param name="a_decodedText"> text decoded using a chromosome </param> /// <param name="a_dataSetnGrams"> frequences of n-grams from our dataset </param> /// /// <returns> /// int score of the chromosome /// </returns> /// /// <author> /// Ian Cordova 4:30am 5/3/2018 /// </author> static private int ScoreChromosome(string a_decodedText, Dictionary <string, int> a_dataSetnGrams) { double score = 0; Dictionary <string, int> decodedTextBiGrams = CipherUtility.FindnGrams(2, a_decodedText); // rate each entry and add all of them together to score the chromosome as a whole foreach (var entry in decodedTextBiGrams) { if (a_dataSetnGrams.ContainsKey(entry.Key)) { score += entry.Value * Math.Log(a_dataSetnGrams[entry.Key], 2); } } return((int)score); }
public void DecryptionEmptyAesKeyTest() { String tempAeskey = CipherUtility.TemporaryAESKeyDelete(); Boolean testSuccessful = false; try { CipherUtility.Decrypt("Teststring", "Teststting"); } catch { testSuccessful = CipherUtility.TemporaryAESKeyRestore(tempAeskey); } Assert.IsTrue(testSuccessful); }
public async Task ReceiveAsync(AuthenticationTokenReceiveContext context) { var allowedOrigin = context.OwinContext.Get <string>(Constant.OAuthorization_OAuth_ClientAllowedOrigin); context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); var hashedTokenId = CipherUtility.GetHash(context.Token); var refreshToken = _refreshTokenService.FindById(hashedTokenId); if (refreshToken != null) { // Get protectedTicket from RefreshToken class context.DeserializeTicket(refreshToken.ProtectedTicket); var resultRemove = _refreshTokenService.RemoveById(hashedTokenId); } }
/// <summary> /// Allows me to add data to the dataset of bigrams by just changing which file is specified. /// Loads the data from the file (Note: file does not get substantially larger as data is added. There is a maximum of /// 676 possible bi-grams, so adding data only approaches that number of lines while increasing the count /// next to each existing bi-gram. /// </summary> /// /// <author> /// Ian Cordova - 4:00pm 5/4/2018 /// </author> private static void AddDataToDataSet() { var allBiGrams = CipherUtility.GetTrainingBiGrams(); var newBiGrams = new Dictionary <string, int>(); string fullText = ""; string destPath = "C:\\Users\\icordova\\Source\\Repos\\CipherBreaker\\CipherTrainingData\\DataSetBigrams.txt"; string path = "C:\\Users\\icordova\\Source\\Repos\\CipherBreaker\\CipherTrainingData\\twocities.txt"; using (FileStream fs = File.Open(path, FileMode.Open)) using (BufferedStream bs = new BufferedStream(fs)) using (StreamReader sr = new StreamReader(bs)) { string line; while ((line = sr.ReadLine()) != null) { line = line.ToUpper(); fullText += line; // this is so ineffective and slow, but im lazy and only have to run this once } } newBiGrams = CipherUtility.FindnGrams(2, fullText); foreach (var entry in newBiGrams) { if (allBiGrams.ContainsKey(entry.Key)) { allBiGrams[entry.Key] += entry.Value; } else { allBiGrams.Add(entry.Key, 1); } } File.WriteAllText(destPath, ""); using (StreamWriter biGramFile = new StreamWriter(destPath)) { allBiGrams = (from entry in allBiGrams orderby entry.Value descending select entry) .ToDictionary(pair => pair.Key, pair => pair.Value); foreach (var entry in allBiGrams) { biGramFile.WriteLine("[{0} {1}]", entry.Key, entry.Value); } } }
/// <summary> /// This is a method that is only called when creating our reference/training set of data. /// ie it should be only called once, and not during normal project run time. This method /// should probably be a separate entity in the form of a separate program or a script, but /// since it uses the same functionality that the main project does I am including it here /// to see everything that was done to achieve the finished result /// </summary> /// /// <returns> /// void - but reads/writes to files /// </returns> /// /// <author> /// Ian Cordova - 6:00pm 4/25/2018 /// </author> private static void GetnGramsFromDataSet() { // dictionaries to store all n-grams and their number of occurances [n-gram, count] Dictionary <string, int> bigrams = new Dictionary <string, int>(); Dictionary <string, int> trigrams = new Dictionary <string, int>(); // temporary storage for grams after they are found List <string> grams = new List <string>(); string fullText = ""; string path = "C:\\Users\\icordova\\Source\\Repos\\CipherBreaker\\CipherTrainingData\\DataSet.csv"; using (FileStream fs = File.Open(path, FileMode.Open)) using (BufferedStream bs = new BufferedStream(fs)) using (StreamReader sr = new StreamReader(bs)) { string line; while ((line = sr.ReadLine()) != null) { line = line.ToUpper(); fullText += line; // this is so ineffective and slow, but im lazy and only have to run this once } bigrams = CipherUtility.FindnGrams(2, fullText); } // write dictionaries to files using (StreamWriter biGramFile = new StreamWriter("C:\\Users\\icordova\\Source\\Repos\\CipherBreaker\\CipherTrainingData\\DataSetBigrams.txt")) { bigrams = (from entry in bigrams orderby entry.Value descending select entry) .ToDictionary(pair => pair.Key, pair => pair.Value); foreach (var entry in bigrams) { biGramFile.WriteLine("[{0} {1}]", entry.Key, entry.Value); } } }
/// <summary> /// Decrypt method /// </summary> /// <param name="algorithm">Encryption algorithm to use</param> /// <param name="encryptedText">Encrypted text to decrypt</param> /// <param name="password">A password is a word or string of characters used for user authentication to prove identity or access approval to gain access to a resource, which is to be kept secret from those not allowed access.</param> /// <param name="salt">In cryptography, a salt is random data that is used as an additional input to a one-way function that "hashes" data, a password or passphrase.</param> /// <returns>Decrypted text (plain text)</returns> public static string Decrypt(ServiceProvider algorithm, string encryptedText, string password, string salt) { switch (algorithm) { case ServiceProvider.AES: return(CipherUtility.Decrypt <AesManaged>(encryptedText, password, salt)); case ServiceProvider.DES: return(CipherUtility.Decrypt <DESCryptoServiceProvider>(encryptedText, password, salt)); case ServiceProvider.RC2: return(CipherUtility.Decrypt <RC2CryptoServiceProvider>(encryptedText, password, salt)); case ServiceProvider.Rijndael: return(CipherUtility.Decrypt <RijndaelManaged>(encryptedText, password, salt)); case ServiceProvider.TripleDES: return(CipherUtility.Decrypt <TripleDESCryptoServiceProvider>(encryptedText, password, salt)); default: return(null); } }
public void TurnMaster(IPEndPoint endPoint, string targetTile) { #region bogstavertiltal string letter = targetTile.Remove(1); string number = targetTile.Substring(1); int posY = 123; switch (letter) { case "a": posY = 0; break; case "b": posY = 1; break; case "c": posY = 2; break; case "d": posY = 3; break; case "e": posY = 4; break; case "f": posY = 5; break; case "g": posY = 6; break; case "h": posY = 7; break; case "i": posY = 8; break; case "j": posY = 9; break; } #endregion if (endPoint == playerOneEP) { if (!playerTwoMap.CheckTile(int.Parse(number), posY)) { string sData = CipherUtility.Encrypt <AesManaged>(Program.Usernames[playerOneEP] + " missed at position: " + letter + number, "password", "salt"); lock (Program.MsgsLock) { Program.Msgs.Add(Program.InfoSender[playerOneEP], sData); Program.Msgs.Add(Program.InfoSender[playerTwoEP], sData); } playerOneTurn = false; } else { string sData = CipherUtility.Encrypt <AesManaged>(Program.Usernames[playerOneEP] + " hit at position: " + letter + number, "password", "salt"); lock (Program.MsgsLock) { Program.Msgs.Add(Program.InfoSender[playerOneEP], sData); Program.Msgs.Add(Program.InfoSender[playerTwoEP], sData); } playerTwoMap.UnOccupyTile(int.Parse(number), posY); if (playerTwoMap.Win()) { sData = CipherUtility.Encrypt <AesManaged>(Program.Usernames[playerOneEP] + " won!", "password", "salt"); lock (Program.MsgsLock) { Program.Msgs.Add(Program.InfoSender[playerOneEP], sData); Program.Msgs.Add(Program.InfoSender[playerTwoEP], sData); } lock (Program.ConnectedUsersLock) { Program.MatchedUsers.Remove(playerTwoEP); Program.MatchedUsers.Remove(playerOneEP); Program.ConnectedUsers.Add(playerTwoEP); Program.ConnectedUsers.Add(playerOneEP); } } } } else if (endPoint == playerTwoEP) { if (!playerOneMap.CheckTile(int.Parse(number), posY)) { string sData = CipherUtility.Encrypt <AesManaged>(Program.Usernames[playerTwoEP] + " missed at position: " + letter + number, "password", "salt"); lock (Program.MsgsLock) { Program.Msgs.Add(Program.InfoSender[playerOneEP], sData); Program.Msgs.Add(Program.InfoSender[playerTwoEP], sData); } playerOneTurn = true; } else { string sData = CipherUtility.Encrypt <AesManaged>(Program.Usernames[playerTwoEP] + " hit at position: " + letter + number, "password", "salt"); lock (Program.MsgsLock) { Program.Msgs.Add(Program.InfoSender[playerOneEP], sData); Program.Msgs.Add(Program.InfoSender[playerTwoEP], sData); } playerOneMap.UnOccupyTile(int.Parse(number), posY); if (playerOneMap.Win()) { sData = CipherUtility.Encrypt <AesManaged>(Program.Usernames[playerTwoEP] + " won!", "password", "salt"); lock (Program.MsgsLock) { Program.Msgs.Add(Program.InfoSender[playerOneEP], sData); Program.Msgs.Add(Program.InfoSender[playerTwoEP], sData); } lock (Program.ConnectedUsersLock) { Program.MatchedUsers.Remove(playerTwoEP); Program.MatchedUsers.Remove(playerOneEP); Program.ConnectedUsers.Add(playerTwoEP); Program.ConnectedUsers.Add(playerOneEP); } } } } }
public void EncryptionExceptionTest2() { string salt = "Teststing"; CipherUtility.Encrypt("", salt); }
public void CipherUtilityConstructorTest() { CipherUtility target = new CipherUtility(); Assert.IsNotNull(target); }
/// <summary> /// Generates an initial chromosome to compare against our frequency data. /// A chromosome is a potential solution to our problem that we will refine /// the initial chromosome is just a random mapping of letters /// </summary> /// /// <returns> /// Dictionary containing the alphabet as keys and random, unique characters as values /// </returns> /// /// <author> /// Ian Cordova - 7:00pm, 5/2/2018 /// </author> private static Dictionary <char, char> GenerateChromosome(string a_cipherText, Dictionary <string, int> a_dataSet) { Dictionary <char, char> initialChromosome = new Dictionary <char, char>(); Dictionary <string, int> cipherTextBiGrams = new Dictionary <string, int>(CipherUtility.FindnGrams(2, a_cipherText)); List <char> alphabet = new List <char>(m_Alphabet); HashSet <char> topCipherTextChars = new HashSet <char>(GetCommonLetters(cipherTextBiGrams)); HashSet <char> topDataSetChars = new HashSet <char>(GetCommonLetters(a_dataSet)); List <char> topChars = new List <char>(topDataSetChars.ToList()); Random rand = new Random(); int randLetter; // fill in chromosome with most likely possibilites foreach (var letter in topCipherTextChars) { randLetter = rand.Next(0, topChars.Count - 1); initialChromosome.Add(letter, topChars[randLetter]); alphabet.Remove(topChars[randLetter]); topChars.RemoveAt(randLetter); } // fill in rest of chromosome for (int i = 0; i < 26;) { randLetter = rand.Next(0, alphabet.Count); // already have this key if (initialChromosome.ContainsKey(m_Alphabet[i])) { i++; continue; } // already have this value if (initialChromosome.ContainsValue(alphabet[randLetter])) { continue; } // save key and value to new chromosome else { initialChromosome.Add(m_Alphabet[i], alphabet[randLetter]); i++; } } return(initialChromosome); }
public void EncryptionExceptionTest1() { string value = "Teststing"; CipherUtility.Encrypt(value, ""); }
public static void HandleClient(object obj) { TcpClient client = (TcpClient)obj; StreamReader sReader = new StreamReader(client.GetStream(), Encoding.ASCII); StreamWriter sWriter = new StreamWriter(client.GetStream(), Encoding.ASCII); string sData = null; IPEndPoint endPoint = (IPEndPoint)client.Client.RemoteEndPoint; IPEndPoint localEndPoint = (IPEndPoint)client.Client.LocalEndPoint; Console.WriteLine(endPoint + " connected!"); infoSender.Add(endPoint, sWriter); string simon = "Enter username: "******"password", "salt"); sWriter.WriteLine(encryptedd); sWriter.Flush(); try { sData = sReader.ReadLine(); string dedcrypt = CipherUtility.Decrypt <AesManaged>(sData, "password", "salt"); usernames.Add(endPoint, dedcrypt); } catch (Exception e) { Console.WriteLine(client.Client.RemoteEndPoint + " disconnected!"); UserDisconnected(endPoint); } lock (connectedUsersLock) { connectedUsers.Add(endPoint); Console.WriteLine("Queued users: {0}", connectedUsers.Count); } while (client.Connected) { try { sData = sReader.ReadLine(); sData = CipherUtility.Decrypt <AesManaged>(sData, "password", "salt"); //Console.WriteLine("Encrypted data recieved: " + sData); if (sData.Length > 2) { foreach (GameWorld gw in gwList) { if (gw.playerOneEP == endPoint || gw.playerTwoEP == endPoint) { gw.StringToMap(endPoint, sData); } } } #region if (!dataReceived) { if (sData != "baae866ac1607d6fe25b3b57406d22d28e1bd2f9027daabfbbc44cf11e5e6050") { dataReceived = true; Console.WriteLine("Client doesnt have the right MD5!"); string errorOne = "Your MD5 is not RIGHT!, disconnecting."; string MD5Error = CipherUtility.Encrypt <AesManaged>(errorOne, "password", "salt"); sWriter.WriteLine(MD5Error); sWriter.Flush(); client.Close(); break; } } #endregion Console.WriteLine("Data recieved and decrypted: " + sData); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(client.Client.RemoteEndPoint + " disconnected!"); UserDisconnected(endPoint); } if (matchedUsers.Contains(endPoint)) { try { foreach (GameWorld gw in gwList) { if (gw.playerOneEP == endPoint) { if (gw.PlayerOneTurn) { gw.TurnMaster(endPoint, sData); } break; } else if (gw.playerTwoEP == endPoint) { if (!gw.PlayerOneTurn) { gw.TurnMaster(endPoint, sData); } break; } } } catch (Exception e) { Console.WriteLine(e.Message); } } } }
public void Read() { string incomingData = null; _sReader = new StreamReader(_client.GetStream(), Encoding.ASCII); while (_isConnected) { try { incomingData = _sReader.ReadLine(); string decrypted = CipherUtility.Decrypt <AesManaged>(incomingData, "password", "salt"); if (decrypted == "Matched") { Console.Clear(); Console.SetCursorPosition(40, 40); Program.Matched = true; Console.Clear(); gw.GameSetup(); gw.Play(); string sData = CipherUtility.Encrypt <AesManaged>(gw.YourMap.ReadMap(), "password", "salt"); _sWriter.WriteLine(sData); _sWriter.Flush(); } else { string tileShot = decrypted.Substring(decrypted.Length - 2); int posY = 0; #region Switch switch (tileShot.Remove(1)) { case "a": posY = 0; break; case "b": posY = 1; break; case "c": posY = 2; break; case "d": posY = 3; break; case "e": posY = 4; break; case "f": posY = 5; break; case "g": posY = 6; break; case "h": posY = 7; break; case "i": posY = 8; break; case "j": posY = 9; break; } #endregion if (decrypted.Contains("missed")) { if (decrypted.Contains(username)) { gw.EnemyMap.MarkTile(int.Parse(tileShot.Substring(1)), posY, 'M', ConsoleColor.Red); } else { gw.YourMap.MarkTile(int.Parse(tileShot.Substring(1)), posY, 'M', ConsoleColor.Green); } } else if (decrypted.Contains("hit")) { if (decrypted.Contains(username)) { gw.EnemyMap.MarkTile(int.Parse(tileShot.Substring(1)), posY, 'H', ConsoleColor.Green); } else { gw.YourMap.MarkTile(int.Parse(tileShot.Substring(1)), posY, 'H', ConsoleColor.Red); } } Console.WriteLine(decrypted); ClearCurrentConsoleLine(); } } catch (Exception e) { Console.WriteLine("\n" + e.Message); Console.ReadLine(); } } }
public void HandleCommunication() { _sWriter = new StreamWriter(_client.GetStream(), Encoding.ASCII); _sReader = new StreamReader(_client.GetStream(), Encoding.UTF8); _isConnected = true; string sData = null; sData = sha256Calc; Console.WriteLine(sha256Calc); string encrypted = CipherUtility.Encrypt <AesManaged>(sData, "password", "salt"); _sWriter.WriteLine(encrypted); _sWriter.Flush(); Thread readThread = new Thread(Read); readThread.Start(); sData = Console.ReadLine(); // Username username = sData; encrypted = CipherUtility.Encrypt <AesManaged>(sData, "password", "salt"); _sWriter.WriteLine(encrypted); try { _sWriter.Flush(); } catch (Exception e) { Console.WriteLine(e.Message); } while (_isConnected) { /* string md5Encrypt = CipherUtility.Encrypt<AesManaged>(sha256Calc, "password", "salt"); * _sWriter.WriteLine(md5Encrypt); * _sWriter.Flush();*/ if (gw.ShipsPlaced) { sData = Console.ReadLine(); if (Program.Matched) { if (sData.Length > 1) { string letter = sData.Remove(1); string number = sData.Substring(1); if (letterArray.Contains(letter) && numberArray.Contains(number)) { encrypted = CipherUtility.Encrypt <AesManaged>(sData, "password", "salt"); _sWriter.WriteLine(encrypted); if (!Program.Matched) { Console.WriteLine("Waiting for opponent.."); } try { _sWriter.Flush(); } catch (Exception e) { Console.WriteLine(e.Message); } } else { Console.WriteLine("Wrong input format! Enter coordinates in this format 'a5', 'c3' etc."); } } } } } }