private static ServerConnection ProcessServer(Socket s) { byte[] test = new byte[23]; s.Receive(test); Console.WriteLine(Encoding.ASCII.GetString(test)); ServerConnection conn = new ServerConnection(); conn.Sock = s; conn.Aes = new AesCryptoServiceProvider(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { using (RSACng rsa = new RSACng(3072)) { var bytes = new byte[3072]; conn.Sock.Receive(bytes); rsa.ImportRSAPublicKey(bytes, out _); conn.Sock.Send(rsa.Encrypt(conn.Aes.Key, RSAEncryptionPadding.Pkcs1)); } } else { using (RSAOpenSsl rsa = new RSAOpenSsl(3072)) { var bytes = new byte[3072]; conn.Sock.Receive(bytes); rsa.ImportRSAPublicKey(bytes, out _); conn.Sock.Send(rsa.Encrypt(conn.Aes.Key, RSAEncryptionPadding.Pkcs1)); } } var headerBytes = new byte[20]; conn.Sock.Receive(headerBytes); conn.Aes.IV = headerBytes.Take(16).ToArray(); int msgLength = BitConverter.ToInt32(headerBytes.Skip(16).Take(4).ToArray()); var encryptedBytes = new byte[msgLength]; conn.Sock.Receive(encryptedBytes); string msg; using (MemoryStream ms = new MemoryStream(encryptedBytes)) { using (CryptoStream cs = new CryptoStream(ms, conn.Aes.CreateDecryptor(), CryptoStreamMode.Read)) { using (StreamReader sr = new StreamReader(cs)) { msg = sr.ReadToEnd(); } } } if (msg != "OK!") { throw new Exception("Server didn't return \"OK!\""); } return(conn); }
private static RSA BuildRsaPublicKey(byte[] encodedData) { RSA rsa = new RSAOpenSsl(); try { rsa.ImportRSAPublicKey(new ReadOnlySpan <byte>(encodedData), out _); } catch (Exception) { rsa.Dispose(); throw; } return(rsa); }