private static extern int WNetAddConnection2(NetResource netResource, string password, string username, int flags);
private void DoWorkConnect(object sender, DoWorkEventArgs eventArgs) { try { IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(Ip), Port); uclient = new UdpClient(); uclient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); uclient.DontFragment = true; uclient.Connect(ipep); tcpclnt = new TcpClient(); Console.WriteLine("Connecting....."); Status = 2; tcpclnt.NoDelay = true; tcpclnt.Connect(Ip, Port); Console.WriteLine("Connected"); tcpclnt.GetStream().Write(publicKey, 0, publicKey.Length); byte[] serverPublicKey = new byte[72]; tcpclnt.GetStream().Read(serverPublicKey, 0, 72); byte[] derivedKey = exch.DeriveKeyMaterial(CngKey.Import(serverPublicKey, CngKeyBlobFormat.EccPublicBlob)); StreamWriter stream = new StreamWriter(tcpclnt.GetStream()); stream.WriteLine(Username); stream.Flush(); Aes aes = new AesCryptoServiceProvider(); aes.Key = derivedKey; byte[] bytes = new byte[aes.BlockSize / 8]; bytes.Initialize(); System.Buffer.BlockCopy(Username.ToCharArray(), 0, bytes, 0, bytes.Length > Username.Length * sizeof(char) ? Username.Length * sizeof(char) : bytes.Length); aes.IV = bytes; ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); MemoryStream ms = new MemoryStream(64); CryptoStream csEncrypt = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); byte[] passArr = Encoding.UTF8.GetBytes(Password); csEncrypt.Write(passArr, 0, passArr.Length); csEncrypt.Close(); byte[] tosend = ms.ToArray(); string encpass = Convert.ToBase64String(tosend, 0, tosend.Length); stream.WriteLine(encpass); stream.Flush(); byte[] auth = new byte[sizeof(bool)]; tcpclnt.GetStream().Read(auth, 0, sizeof(bool)); bool result = BitConverter.ToBoolean(auth, 0); eventArgs.Result = result; } catch (Exception ioe) { eventArgs.Result = false; } if ((bool)eventArgs.Result) { Action act = new Action(() => { var netResource = new NetResource() { Scope = ResourceScope.GlobalNetwork, ResourceType = ResourceType.Disk, DisplayType = ResourceDisplaytype.Share, RemoteName = "\\\\" + Ip + "\\C" }; var result = WNetAddConnection2( netResource, Password, null, 0x00000004 | 0x00000008 | 0x1000); if (result != 0) { Console.WriteLine("Result not zero: " + result); } }); Thread t = new Thread(() => act()); t.Start(); } }