public void Challenge10_CBCMode() { var data = Encoding.UTF8.GetBytes("test"); byte[] cipher; byte[] decrypted; byte[] key = Encoding.UTF8.GetBytes("ss012345678901234567890123456789"); byte[] iv = new byte[16]; cipher = MyAes.EncryptCbcPkcs7(data, iv, key); using (var aes2 = new AesCryptoServiceProvider()) { aes2.Key = key; aes2.IV = iv; using (var dec = aes2.CreateDecryptor()) decrypted = dec.TransformFinalBlock(cipher, 0, cipher.Length); } Assert.Equal(data, decrypted); cipher = Convert.FromBase64String(File.ReadAllText("10.txt")); using (var aes2 = new AesCryptoServiceProvider()) { aes2.Key = Encoding.UTF8.GetBytes("YELLOW SUBMARINE"); aes2.IV = iv; using (var dec = aes2.CreateDecryptor()) decrypted = dec.TransformFinalBlock(cipher, 0, cipher.Length); var text = Encoding.UTF8.GetString(decrypted); Assert.StartsWith("I'm back and I'm ringin' the bell ", text); } }
/// <summary> /// Отправляет сырые данные на сокет /// </summary> /// <param name="rawData">Последовательность байт</param> public void Send(byte[] rawData) { lock (Locker) { byte[] identityPacketData = new byte[] { (byte)196, (byte)12 }; if (Aes256Key != null) { rawData = MyAes.EncryptBytes(rawData, Aes256Key, MyAes.Iv); } byte[] lengthBytes = BitConverter.GetBytes(rawData.Length); TcpClient.GetStream().Write(identityPacketData, 0, identityPacketData.Length); TcpClient.GetStream().Write(lengthBytes, 0, lengthBytes.Length); // Если работает шифрование, то шифруем все сообщение TcpClient.GetStream().Write(rawData, 0, rawData.Length); TcpClient.GetStream().Flush(); } }
public void Challenge12_Byte_at_a_time_ECB_decryption_simple() { var secretSuffix = Convert.FromBase64String( "Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkgaGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBqdXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUgYnkK"); using (var rnd = RandomNumberGenerator.Create()) { var key = new byte[16]; rnd.GetBytes(key); Func <ReadOnlyMemory <byte>, byte[]> encrypt = data => MyAes.EncryptEcb(data.Span, secretSuffix, key); var blockSize = AesOracle.GuessBlockSize(encrypt); Assert.Equal(16, blockSize); var payload = new byte[3 * blockSize]; var encrypted = encrypt(payload); Assert.Equal(CipherMode.ECB, AesOracle.GuessMode(encrypted, blockSize)); var calculatedPrefixLength = AesOracle.GetPrefixLength(blockSize, encrypt); Assert.Equal(0, calculatedPrefixLength); var decrypted = AesOracle.ByteAtATimeEcb(blockSize, encrypt); var plainText = Encoding.UTF8.GetString(decrypted); var secretText = Encoding.UTF8.GetString(secretSuffix); Assert.Equal(secretText, plainText); } }
public static bool AddAppUser(string email, string password) { bool returnValue = false; using (var db = new DbModel()) { var users = from x in db.APP_USER where x.EMAIL.Equals(email) select x; if (!users.Any()) { APP_USER newUser = new APP_USER() { EMAIL = email, PASSWORD = MyAes.EncryptStringToString(password) }; db.APP_USER.Add(newUser); db.SaveChanges(); returnValue = true; } } return(returnValue); }
public void Challenge07_DecryptAesEcb() { var base64 = File.ReadAllText("7.txt").Replace("\n", ""); var cipher = Convert.FromBase64String(base64); Assert.Equal("I'm back and I'm ringin' the bell ", Encoding.UTF8.GetString(MyAes.DecryptEcb(cipher, Encoding.UTF8.GetBytes("YELLOW SUBMARINE"))).Split('\n')[0]); }
public void Challenge18_CTR_stream_cipher_mode() { var input = Convert.FromBase64String("L77na/nrFsKvynd6HzOoG7GHTLXsTVu9qvY/2syLXzhPweyyMTJULu/6/kXX0KSvoOLSFQ=="); ulong nonce = 0; var key = Encoding.UTF8.GetBytes("YELLOW SUBMARINE"); Assert.Equal("Yo, VIP Let's kick it Ice, Ice, baby Ice, Ice, baby ", Encoding.UTF8.GetString(MyAes.EncryptDecryptCtr(input, nonce, key))); nonce = 13; var plainText = "test"; var encrypted = MyAes.EncryptDecryptCtr(Encoding.UTF8.GetBytes(plainText), nonce, key); Assert.Equal(plainText, Encoding.UTF8.GetString(MyAes.EncryptDecryptCtr(encrypted, nonce, key))); }
public static void AddPasswordHistory(DateTime dateHist, string passwordHist, int dataId) { PASSWORD_HISTORY hist = new PASSWORD_HISTORY() { DATA_ID = dataId, DATE_HIST = dateHist, PASSWORD_HIST = MyAes.EncryptStringToString(passwordHist) }; using (var db = new DbModel()) { db.PASSWORD_HISTORY.Add(hist); db.SaveChanges(); } }
public static void AddUserData(string comment, string servName, string servPassword, int userId) { USER_DATA data = new USER_DATA() { APP_USER_ID = userId, COMMENT = comment, SERV_NAME = servName, SERV_PASSWORD = MyAes.EncryptStringToString(servPassword) }; using (var db = new DbModel()) { db.USER_DATA.Add(data); db.SaveChanges(); } }
public void CbcLibraryEncryptCustomDecrypt() { using (var rnd = RandomNumberGenerator.Create()) { var input = new byte[42]; rnd.GetBytes(input); var key = new byte[16]; rnd.GetBytes(key); var iv = new byte[16]; rnd.GetBytes(iv); var encrypted = MyAes._LibraryEncrypt(input, iv, key, CipherMode.CBC); var decrypted = MyAes._CustomDecryptCbcPkcs7(encrypted, iv, key); Assert.Equal(input, decrypted.ToArray()); } }
public static void UpdateUserData(string comment, string servName, string servPassword, int id) { using (var db = new DbModel()) { var updateData = (from x in db.USER_DATA where x.ID == id select x).SingleOrDefault(); if (updateData != null) { updateData.COMMENT = comment; updateData.SERV_NAME = servName; updateData.SERV_PASSWORD = MyAes.EncryptStringToString(servPassword); db.SaveChanges(); } } }
public static AppUserDto SelectAppUser(string email, string password) { using (var db = new DbModel()) { var user = (from x in db.APP_USER where x.EMAIL.Equals(email) select new AppUserDto() { Email = x.EMAIL, Id = x.ID, Password = x.PASSWORD }).SingleOrDefault(); if (user != null && user.Password.Equals(MyAes.EncryptStringToString(password))) { return(user); } return(null); } }
private (List <byte[]> encryptedLines, List <string> plainTextLines) ReadAndEncryptWithCTR(string fileName, ulong nonce) { var lines = File.ReadAllLines(fileName); var encryptedLines = new List <byte[]>(lines.Length); var plainTextLines = new List <string>(lines.Length); using (var rnd = RandomNumberGenerator.Create()) { var key = new byte[16];// { (byte)0x03, (byte)0x39, (byte)0x1e, (byte)0xb9, (byte)0x0f, (byte)0xf7, (byte)0xbc, (byte)0xe4, (byte)0x77, (byte)0x3e, (byte)0x9f, (byte)0x58, (byte)0xcc, (byte)0x9c, (byte)0xd3, (byte)0x28 }; ; rnd.GetBytes(key); foreach (var line in lines) { var plainBytes = Convert.FromBase64String(line); var plainText = Encoding.UTF8.GetString(plainBytes); plainTextLines.Add(plainText); var encrypted = MyAes.EncryptDecryptCtr(plainBytes, nonce, key); encryptedLines.Add(encrypted); } } return(encryptedLines, plainTextLines); }
public void Challenge17_CBC_padding_oracle() { var lines = File.ReadAllLines("17.txt"); using (var rnd = RandomNumberGenerator.Create()) { //var input = Convert.FromBase64String(lines[rnd.GetInt(0, lines.Length)]); foreach (var line in lines) { var input = Convert.FromBase64String(line); var key = new byte[16]; rnd.GetBytes(key); var iv = new byte[16]; rnd.GetBytes(iv); var encrypted = MyAes.EncryptCbcPkcs7(input, iv, key); var decrypted = CbcPaddingOracle.Decrypt(encrypted, iv, key); Assert.Equal(input, decrypted.ToArray()); } } }
private void ReceiveDataStart(int receiveBufferLength) { try { _disconnectTimer.Stop(); _disconnectTimer.Start(); _disconnectTimer.Elapsed += (sender, args) => { Console.WriteLine("Client disconnected by timeout"); CloseConnect(); }; using (NetworkStream stream = TcpClient.GetStream()) { while (TcpClient.Connected) { if (TcpClient.Available < HeaderLength) { Thread.Sleep(5); continue; } int messageLength = ReceiveHeaderData(stream); if (messageLength > _server.MaxReceivePacketLength) { CloseConnect(); return; } int remaining = messageLength; byte[] finalDataBuffer = new byte[messageLength]; int index = 0; while (remaining > 0) { if (remaining < receiveBufferLength) { receiveBufferLength = remaining; } while (TcpClient.Available < receiveBufferLength) { Thread.Sleep(5); } byte[] buffer = new byte[receiveBufferLength]; stream.Read(buffer, 0, receiveBufferLength); for (int i = 0; i < buffer.Length; i++) { finalDataBuffer[index++] = buffer[i]; } remaining -= receiveBufferLength; } if (Aes256Key != null) { finalDataBuffer = MyAes.DecryptBytes(finalDataBuffer, Aes256Key, MyAes.Iv); } Console.WriteLine("Readed from client bytes length " + (finalDataBuffer.Length)); if (ByteArrayCompare(finalDataBuffer, PingData)) { Send(PongData); _disconnectTimer.Stop(); _disconnectTimer.Start(); Console.WriteLine("Ping data received " + (messageLength + HeaderLength) + " bytes. Pong data sent"); } else { NewData?.Invoke(finalDataBuffer); try { object packet = null; int packetId = BitConverter.ToInt32(finalDataBuffer.Take(4).ToArray(), 0); if (_server.MessageEncryptionEnabled) { if (this.Aes256Key == null) { if (packetId != -122030 && packetId != -42142) { Console.WriteLine("Пришел пакет, который не ожидался"); continue; } } } NewPacket?.Invoke(ref packetId, (t) => { using (MemoryStream ms = new MemoryStream(finalDataBuffer.Skip(4).ToArray())) using (BsonReader reader = new BsonReader(ms)) { JsonSerializer serializer = new JsonSerializer(); packet = serializer.Deserialize(reader, t); } return((Packet)packet); }, this); } catch (Exception e) { Console.WriteLine(e.Message + " " + e.StackTrace); } } } } } catch (Exception e) { // Debug Console.WriteLine(e.Message + " " + e.StackTrace); } finally { Disconnected?.Invoke(this); CloseConnect(); } }
public void Run(int receiveBufferLength = 4096) { try { using (NetworkStream stream = _client.GetStream()) { while (_client.Connected) { if (_client.Available < HeaderLength) { Thread.Sleep(5); continue; } int messageLength = ReceiveHeaderData(stream); int remaining = messageLength; byte[] finalDataBuffer = new byte[messageLength]; int index = 0; while (remaining > 0) { if (remaining < receiveBufferLength) { receiveBufferLength = remaining; } while (_client.Available < receiveBufferLength) { Thread.Sleep(5); } byte[] buffer = new byte[receiveBufferLength]; stream.Read(buffer, 0, receiveBufferLength); for (int i = 0; i < buffer.Length; i++) { finalDataBuffer[index++] = buffer[i]; } remaining -= receiveBufferLength; } if (_fluffyNetClient.Aes256Key != null) { finalDataBuffer = MyAes.DecryptBytes(finalDataBuffer, _fluffyNetClient.Aes256Key, MyAes.Iv); } Console.WriteLine("Readed data from socket " + finalDataBuffer.Length + " bytes"); if (!ByteArrayCompare(PongData, finalDataBuffer)) { NewData?.Invoke(finalDataBuffer); } } } } catch (Exception e) { // Debug Console.WriteLine(e.Message + " " + e.StackTrace); } finally { _fluffyNetClient.CloseConnect(); Disconnected?.Invoke(_fluffyNetClient); } }