برای مشاهده مفیدترین ارسال در این موضوع اینجا کلیک کنید

نمایش نتایج: از شماره 1 تا 6 از مجموع 6
  1. #1
    مدیر بازنشسته
    تاریخ عضویت
    2011 June
    محل سکونت
    گرگان
    ارسال ها
    1,170
    تشکر
    62
    تشکر شده 1,587 بار در 809 پست
    نوشته های وبلاگ
    49


    2 امتياز مثبت از 2 راي
    آيا اين پست براي شما سودمند بود؟ بله | خیر

    پروژه Chatroom در سی شارپ(بصورت قدم به قدم)

    سلام.
    کدای این پستی که میخوام بذارم یه مقدار وقت گیرن و اگه اجازه بدین در چند نوبت میذارم.
    ممنون از شما.

    این تصویر برنامه ایه که باید نوشته بشه:


    و این مطلب پایین توضیح تصویر بالاست:

    Input ---> output
    ------ Form1 --------
    streamWrite, streamReader
    ------ Form2 --------
    user ali ---> 300 user is ok (give pass now) , 400 user is not found
    pass 123 ---> 200 authenticated , 401 pass incorrect
    isauth ---> 202 yes, 203 no
    close ---> 201 connection closed


    //signout ---->
    ------ Form3 --------
    onusers ---> 260 user1 user2 ... 402 unauthenticated


    ------ Form4 --------
    Threading


    ------ Form5 ---------
    tell ali " bia inja " ---> 240 told, 403 user is gone
    -------------------- ----> 250 hasan " bia inja "


    ((((((now go to client side)))


    ------ Form6 ---------
    adduser hossein 123 ---> 204 added, 404 user exsited, 502 wrong arguments, 405 you should log out first


    ------ Form7 --------- (MD5)
    save password by hash


    ------ Form8 --------- (Rijndael)
    find a key for secure connection between server and client
    secure ---> 290 key IV


    ------ Form9 --------- (use RSA to implement SSL)
    securessl ---> 291 comodo.com publickey
    securekey rsa(rijndaelKey,publickey) rsa(rijndaelIV,publickey) --> 292 ok


    Input ---> output
    Input ---> output
    Input ---> output
    Input ---> output
    Input ---> output
    Input ---> output


    winYahooServer:

    کلاس مورد نظر:
    using System;
    using System.Collections.Generic;
    //-----------------
    using System.Security.Cryptography;
    using System.Text;
    using System.IO;


    /// <summary>
    /// Summary description for clsSecurity
    /// </summary>
    public class clsSecurity
    {
    public clsSecurity()
    {
    }
    //.ToString("x2") returns hexadecimal format
    public static string ComputeMD5(string str)
    {
    string strResult = "";
    MD5 x = new MD5CryptoServiceProvider();
    byte[] bytesToHash = System.Text.Encoding.UTF8.GetBytes(str);
    bytesToHash = x.ComputeHash(bytesToHash);
    foreach (Byte b in bytesToHash)
    strResult += b.ToString("x2");
    return strResult;
    //return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");


    }


    public static string ComputeSHA1(string str)
    {
    string strResult = "";
    SHA1 x = new SHA1Managed();
    byte[] bytesToHash = System.Text.Encoding.UTF8.GetBytes(str);
    bytesToHash = x.ComputeHash(bytesToHash);
    foreach (Byte b in bytesToHash)
    strResult += b.ToString("x2");
    return strResult;
    //return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "SHA1");


    }
    //توی کومودو
    public static void getRSAkeys(out string strPublicKey, out string strPublicPrivateKey)
    {
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    strPublicKey = rsa.ToXmlString(false);//public
    strPublicPrivateKey = rsa.ToXmlString(true);//public and private
    }


    //encrypt publicKey
    //decrypt public private key


    public static string EncryptRSAwithPublicKey(string strPublicKey, string strText)
    {
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    rsa.FromXmlString(strPublicKey);
    byte[] bs = rsa.Encrypt(Encoding.UTF8.GetBytes(strText), false);
    //ghalat kardi: return Encoding.UTF8.GetString(bs)
    return Convert.ToBase64String(bs);
    }
    public static string DecryptRSAwithPublicPrivateKey(string strPublicPrivateKey, string strEncrypted)
    {
    byte[] bs = Convert.FromBase64String(strEncrypted);
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    rsa.FromXmlString(strPublicPrivateKey);
    byte[] bs2 = rsa.Decrypt(bs, false);
    return Encoding.UTF8.GetString(bs2);
    }


    //signData public private key
    public static string SignWithRSA(string strPublicPrivateKey, string strText)
    {
    byte[] bs = UTF8Encoding.UTF8.GetBytes(strText);
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    rsa.FromXmlString(strPublicPrivateKey);
    byte[] bs2 = rsa.SignData(bs, new SHA1CryptoServiceProvider());
    //rsa.SignHash(bs);
    return Convert.ToBase64String(bs2);
    }


    public static bool VerifySignWithRSA(string strPublicKey, string strText, string strSign)
    {
    byte[] bsSign = Convert.FromBase64String(strSign);
    byte[] bsText= UTF8Encoding.UTF8.GetBytes(strText);
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    rsa.FromXmlString(strPublicKey);
    bool b=rsa.VerifyData(bsText, new SHA1CryptoServiceProvider(), bsSign);
    return b;
    }


    public static string EncryptAES(string plainText, string strKey, string strIV)
    {


    //byte[] Key = Encoding.ASCII.GetBytes(strKey);
    //byte[] IV = Encoding.ASCII.GetBytes(strIV);
    byte[] Key = Convert.FromBase64String(strKey);
    byte[] IV = Convert.FromBase64String(strIV);




    // Check arguments.
    if (plainText == null || plainText.Length <= 0)
    throw new ArgumentNullException("plainText");
    if (Key == null || Key.Length <= 0)
    throw new ArgumentNullException("Key");
    if (IV == null || IV.Length <= 0)
    throw new ArgumentNullException("Key");




    // Declare the streams used
    // to encrypt to an in memory
    // array of bytes.
    MemoryStream msEncrypt = null;
    CryptoStream csEncrypt = null;
    StreamWriter swEncrypt = null;


    // Declare the RijndaelManaged object
    // used to encrypt the data.
    RijndaelManaged aesAlg = null;
    // Declare the bytes used to hold the
    // encrypted data.
    byte[] encrypted = null;


    try
    {
    // Create a RijndaelManaged object
    // with the specified key and IV.
    aesAlg = new RijndaelManaged();
    aesAlg.Key = Key;
    aesAlg.IV = IV;


    // Create a decrytor to perform the stream transform.
    //ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);


    // Create the streams used for encryption.
    msEncrypt = new MemoryStream();
    csEncrypt = new CryptoStream(msEncrypt, aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV), CryptoStreamMode.Write);
    swEncrypt = new StreamWriter(csEncrypt);


    //csEncrypt.Write(byte[] ...)

    //Write all data to the stream.
    swEncrypt.Write(plainText);


    }
    finally
    {
    // Clean things up.


    // Close the streams.
    if (swEncrypt != null)
    swEncrypt.Close();
    if (csEncrypt != null)
    csEncrypt.Close();
    if (msEncrypt != null)
    msEncrypt.Close();


    // Clear the RijndaelManaged object.
    if (aesAlg != null)
    aesAlg.Clear();
    }


    // Return the encrypted bytes from the memory stream.
    return Convert.ToBase64String(msEncrypt.ToArray());


    }


    public static string DecryptAES(string str, string strKey, string strIV)
    {


    //byte[] Key = Encoding.ASCII.GetBytes(strKey);
    //byte[] IV = Encoding.ASCII.GetBytes(strIV);
    byte[] Key = Convert.FromBase64String(strKey);
    byte[] IV = Convert.FromBase64String(strIV);


    byte[] cipherText = Convert.FromBase64String(str);
    // Check arguments.
    if (cipherText == null || cipherText.Length <= 0)
    throw new ArgumentNullException("cipherText");
    if (Key == null || Key.Length <= 0)
    throw new ArgumentNullException("Key");
    if (IV == null || IV.Length <= 0)
    throw new ArgumentNullException("Key");




    // TDeclare the streams used
    // to decrypt to an in memory
    // array of bytes.
    MemoryStream msDecrypt = null;
    CryptoStream csDecrypt = null;
    StreamReader srDecrypt = null;


    // Declare the RijndaelManaged object
    // used to decrypt the data.
    RijndaelManaged aesAlg = null;
    // Declare the string used to hold
    // the decrypted text.
    string plaintext = null;


    try
    {
    // Create a RijndaelManaged object
    // with the specified key and IV.
    aesAlg = new RijndaelManaged();
    aesAlg.Key = Key;
    aesAlg.IV = IV;


    // Create a decrytor to perform the stream transform.
    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);


    // Create the streams used for decryption.
    msDecrypt = new MemoryStream(cipherText);
    csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
    srDecrypt = new StreamReader(csDecrypt);


    // Read the decrypted bytes from the decrypting stream
    // and place them in a string.
    plaintext = srDecrypt.ReadToEnd();
    }
    finally
    {
    // Clean things up.


    // Close the streams.
    if (srDecrypt != null)
    srDecrypt.Close();
    if (csDecrypt != null)
    csDecrypt.Close();
    if (msDecrypt != null)
    msDecrypt.Close();


    // Clear the RijndaelManaged object.
    if (aesAlg != null)
    aesAlg.Clear();
    }


    return plaintext;


    }


    public static string produceKey(int keysize, string hashAlgorithm, int passwordIterations)
    {
    byte[] saltValueBytes = new byte[keysize];
    Random r=new Random();
    r.NextBytes(saltValueBytes);
    string strPhrase = r.NextDouble().ToString();
    PasswordDeriveBytes password = new PasswordDeriveBytes(
    strPhrase,
    saltValueBytes,
    hashAlgorithm,
    passwordIterations);
    byte[] keyBytes = password.GetBytes(keysize);
    string str = Convert.ToBase64String(keyBytes);
    return str; //.Substring(0, 16);
    }
    }




    و فرمهای مربوطه:

    فرم اول:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    //
    using System.Net.Sockets;
    using System.Threading;
    using System.Net;
    using System.IO;


    namespace winYahooServer
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }




    private void Form1_Load(object sender, EventArgs e)
    {


    //Thread t = new Thread(new ThreadStart(Server));
    //t.IsBackground = true;
    //t.Start();
    Server();


    }


    TcpListener listener;
    Socket s;


    private void Server()
    {


    IPAddress localip = IPAddress.Parse("127.0.0.1");


    listener = new TcpListener(localip, 8080);
    listener.Start();




    while (true)
    {
    s = listener.AcceptSocket();
    //Thread t = new Thread(new ThreadStart(ListenIt));
    //t.IsBackground = true;
    //t.Start();
    ListenIt();
    }


    }


    private void ListenIt()
    {
    Socket sok = s;
    NetworkStream ns = new NetworkStream(sok);
    StreamWriter writer = new StreamWriter(ns);
    StreamReader reader = new StreamReader(ns);


    bool shouldBeListen = true;


    while (shouldBeListen)
    {
    string strResponse="";
    string str = reader.ReadLine();
    switch (str.ToLower())
    {
    case "salam":
    strResponse = "201 salam\r\n";
    break;
    case "bye":
    strResponse = ("202 bye\r\n");
    break;
    case "close":
    strResponse = ("203 closed\r\n");
    shouldBeListen = false;
    break;
    default:
    strResponse = ("403 UnKnown Command\r\n");
    break;
    }
    writer.Write(strResponse);
    writer.Flush();
    }
    ns.Close();
    sok.Close();




    }


    }
    }




    فرم دوم:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    //
    using System.Net.Sockets;
    using System.Threading;
    using System.Net;
    using System.IO;


    namespace winYahooServer
    {
    public partial class Form2 : Form
    {
    Dictionary<string, string> users;


    public Form2()
    {
    InitializeComponent();
    }


    private void Form2_Load(object sender, EventArgs e)
    {
    users = new Dictionary<string, string>();
    users["ali"] = "123";
    users["hasan"] = "123";
    users["akbar"] = "123";
    //Thread t = new Thread(new ThreadStart(Server));
    //t.IsBackground = true;
    //t.Start();
    Server();


    }


    TcpListener listener;
    Socket s;


    private void Server()
    {


    IPAddress localip = IPAddress.Parse("127.0.0.1");


    listener = new TcpListener(localip, 8080);
    listener.Start();




    while (true)
    {
    s = listener.AcceptSocket();
    //Thread t = new Thread(new ThreadStart(ListenIt));
    //t.IsBackground = true;
    //t.Start();
    ListenIt();
    }


    }


    private void ListenIt()
    {
    Socket sok = s;
    NetworkStream ns = new NetworkStream(sok);
    StreamWriter writer = new StreamWriter(ns);
    StreamReader reader = new StreamReader(ns);


    bool shouldBeListen = true;

    //for command recognition
    string strcommand="", strarg="";
    string strResponse = "";
    string[] strInputSegment;


    //for saving user
    string strUser="";
    bool isAuthenticated = false;


    while (shouldBeListen)
    {
    string str = reader.ReadLine();
    strInputSegment = str.Split(' ');
    try
    {
    strcommand = strInputSegment[0];
    }
    catch
    {
    strcommand = "error";
    }


    try
    {
    strarg = strInputSegment[1];
    }
    catch
    {
    strarg = "error";
    }


    switch (strcommand.ToLower())
    {
    case "user":
    //hacker:
    //if (isAuthenticated)
    //{
    // strResponse = "497 this connection is assigned to another user, first sign out :P";
    //}
    if (users.ContainsKey(strarg))
    {
    //hackers: isAuthenticated = false;
    strResponse = "300 user is ok (give pass now)\r\n";
    strUser = strarg;
    }
    else
    {
    strResponse = "400 user not found\r\n";
    }
    break;


    case "pass":
    if (users[strUser] == strarg)
    {
    strResponse = "200 authenticated\r\n";
    isAuthenticated=true;
    }
    else
    {
    strResponse = "401 pass incorrect\r\n";
    }


    break;

    case "isauth":
    if (isAuthenticated)
    strResponse = "202 yes\r\n";
    else
    strResponse = "203 no\r\n";
    break;


    case "close":
    strResponse = "201 connection closed\r\n";
    shouldBeListen = false;
    break;


    default:
    strResponse = ("503 UnKnown Command\r\n");
    break;
    }
    writer.Write(strResponse);
    writer.Flush();
    }
    ns.Close();
    sok.Close();




    }


    }
    }




    فرم سوم:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    //
    using System.Net.Sockets;
    using System.Threading;
    using System.Net;
    using System.IO;


    namespace winYahooServer
    {
    public partial class Form3 : Form
    {
    Dictionary<string, string> users;
    string strOnlineUsers = "";


    public Form3()
    {
    InitializeComponent();
    }


    private void Form3_Load(object sender, EventArgs e)
    {
    users = new Dictionary<string, string>();
    users["ali"] = "123";
    users["hasan"] = "123";
    users["akbar"] = "123";


    //Thread t = new Thread(new ThreadStart(Server));
    //t.IsBackground = true;
    //t.Start();
    Server();


    }


    TcpListener listener;
    Socket s;


    private void Server()
    {


    IPAddress localip = IPAddress.Parse("127.0.0.1");


    listener = new TcpListener(localip, 8080);
    listener.Start();




    while (true)
    {
    s = listener.AcceptSocket();
    //Thread t = new Thread(new ThreadStart(ListenIt));
    //t.IsBackground = true;
    //t.Start();
    ListenIt();
    }


    }


    private void ListenIt()
    {
    Socket sok = s;
    NetworkStream ns = new NetworkStream(sok);
    StreamWriter writer = new StreamWriter(ns);
    StreamReader reader = new StreamReader(ns);


    bool shouldBeListen = true;


    //for command recognition
    string strcommand = "", strarg = "";
    string strResponse = "";
    string[] strInputSegment;


    //for saving user's info
    string strUser = "";
    bool isAuthenticated = false;


    while (shouldBeListen)
    {
    string str = reader.ReadLine();
    strInputSegment = str.Split(' ');
    try
    {
    strcommand = strInputSegment[0];
    }
    catch
    {
    strcommand = "error";
    }


    try
    {
    strarg = strInputSegment[1];
    }
    catch
    {
    strarg = "error";
    }


    switch (strcommand.ToLower())
    {
    case "user":
    if (users.ContainsKey(strarg))
    {
    strResponse = "300 user is ok (give pass now)";
    strUser = strarg;
    }
    else
    {
    strResponse = "400 user not found";
    }
    break;


    case "pass":
    if (users[strUser] == strarg)
    {
    strResponse = "200 authenticated";
    isAuthenticated = true;
    //---------------added-----------------
    strOnlineUsers += strUser + " ";
    //------------------
    }
    else
    {
    strResponse = "401 pass incorrect";
    }


    break;


    case "isauth":
    if (isAuthenticated)
    strResponse = "202 yes";
    else
    strResponse = "203 no";
    break;


    case "close":
    //------added---------------
    strOnlineUsers = strOnlineUsers.Replace(strUser + " ", "");
    //---------------------
    strResponse = ("201 connection closed");
    shouldBeListen = false;
    break;
    //------added---------------
    case "onusers":
    if (isAuthenticated)
    strResponse = "260 " + strOnlineUsers;
    else
    strResponse = "402 unauthenticated";
    break;
    //---------------------------
    default:
    strResponse = ("503 UnKnown Command");
    break;
    }
    writer.Write(strResponse + "\r\n");
    writer.Flush();
    }
    ns.Close();
    sok.Close();




    }


    }
    }




    فرم چهارم:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    //
    using System.Net.Sockets;
    using System.Threading;
    using System.Net;
    using System.IO;


    namespace winYahooServer
    {
    public partial class Form4 : Form
    {
    Dictionary<string, string> users;
    string strOnlineUsers = "";


    public Form4()
    {
    InitializeComponent();
    }


    private void Form4_Load(object sender, EventArgs e)
    {
    users = new Dictionary<string, string>();
    users["ali"] = "123";
    users["hasan"] = "123";
    users["akbar"] = "123";
    //-----------uncomment----------------
    Thread t = new Thread(new ThreadStart(Server));
    t.IsBackground = true; // to avoid environment.exit
    t.Start();


    }


    TcpListener listener;
    Socket s;


    private void Server()
    {


    IPAddress localip = IPAddress.Parse("127.0.0.1");


    listener = new TcpListener(localip, 8080);
    listener.Start();




    while (true)
    {
    s = listener.AcceptSocket();
    //-----------uncomment----------------
    Thread t = new Thread(new ThreadStart(ListenIt));
    t.IsBackground = true;
    t.Start();
    }


    }


    private void ListenIt()
    {
    Socket sok = s;
    NetworkStream ns = new NetworkStream(sok);
    StreamWriter writer = new StreamWriter(ns);
    StreamReader reader = new StreamReader(ns);


    bool shouldBeListen = true;


    //for command recognition
    string strcommand = "", strarg = "";
    string strResponse = "";
    string[] strInputSegment;


    //for saving user's info
    string strUser = "";
    bool isAuthenticated = false;


    while (shouldBeListen)
    {
    string str = reader.ReadLine();
    strInputSegment = str.Split(' ');
    try
    {
    strcommand = strInputSegment[0];
    }
    catch
    {
    strcommand = "error";
    }


    try
    {
    strarg = strInputSegment[1];
    }
    catch
    {
    strarg = "error";
    }


    switch (strcommand.ToLower())
    {
    case "user":
    if (users.ContainsKey(strarg))
    {
    strResponse = "300 user is ok (give pass now)";
    strUser = strarg;
    }
    else
    {
    strResponse = "400 user not found";
    }
    break;


    case "pass":
    if (users[strUser] == strarg)
    {
    strResponse = "200 authenticated";
    isAuthenticated = true;
    strOnlineUsers += strUser + " ";
    }
    else
    {
    strResponse = "401 pass incorrect";
    }


    break;


    case "isauth":
    if (isAuthenticated)
    strResponse = "202 yes";
    else
    strResponse = "203 no";
    break;


    case "close":
    strOnlineUsers = strOnlineUsers.Replace(strUser + " ", "");
    strResponse = ("201 connection closed");
    shouldBeListen = false;
    break;
    case "onusers":
    if (isAuthenticated)
    strResponse = "260 " + strOnlineUsers;
    else
    strResponse = "402 unauthenticated";
    break;
    default:
    strResponse = "503 UnKnown Command";
    break;
    }
    writer.Write(strResponse + "\r\n");
    writer.Flush();
    }
    ns.Close();
    sok.Close();


    }


    }
    }




    فرم پنجم:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    //
    using System.Net.Sockets;
    using System.Threading;
    using System.Net;
    using System.IO;


    namespace winYahooServer
    {
    public partial class Form5 : Form
    {
    Dictionary<string, string> users;
    string strOnlineUsers = "";
    //---------------------added----------------
    Dictionary<string, StreamWriter> userWriter = new Dictionary<string, StreamWriter>();
    //DataTable dtMsg = new DataTable();
    //private void InitDtMsg()
    //{
    // dtMsg.Columns.Add("From", typeof(string));
    // dtMsg.Columns.Add("To", typeof(string));
    // dtMsg.Columns.Add("msg", typeof(string));
    // dtMsg.Columns.Add("isSent", typeof(bool));
    //}


    //-----------------


    public Form5()
    {
    //System.Diagnostics.Debugger.Launch();
    InitializeComponent();
    }


    private void Form5_Load(object sender, EventArgs e)
    {
    users = new Dictionary<string, string>();
    users["ali"] = "123";
    users["hasan"] = "123";
    users["akbar"] = "123";


    //InitDtMsg();


    Thread t = new Thread(new ThreadStart(Server));
    t.IsBackground = true;
    t.Start();


    }


    TcpListener listener;
    Socket s;


    private void Server()
    {


    IPAddress localip = IPAddress.Parse("127.0.0.1");


    listener = new TcpListener(localip, 8080);
    listener.Start();




    while (true)
    {
    s = listener.AcceptSocket();
    Thread t = new Thread(new ThreadStart(ListenIt));
    t.IsBackground = true;
    t.Start();

    }


    }


    private void ListenIt()
    {
    Socket sok = s;
    NetworkStream ns = new NetworkStream(sok);
    StreamWriter writer = new StreamWriter(ns);
    StreamReader reader = new StreamReader(ns);


    bool shouldBeListen = true;


    //for command recognition
    string strcommand = "", strarg = "";
    string strResponse = "";
    string[] strInputSegment;
    string str;


    //for saving user's info
    string strUser = "";
    bool isAuthenticated = false;


    while (shouldBeListen)
    {
    //may be error
    //need timer, session timeout=20
    str = "";
    try
    {
    str = reader.ReadLine();
    }
    catch
    {
    Thread.CurrentThread.Abort();
    }
    strInputSegment = str.Split(' ');
    try
    {
    strcommand = strInputSegment[0];
    }
    catch
    {
    strcommand = "error";
    }


    try
    {
    strarg = strInputSegment[1];
    }
    catch
    {
    strarg = "error";
    }


    switch (strcommand.ToLower())
    {
    case "user":
    if (users.ContainsKey(strarg))
    {
    strResponse = "300 user is ok (give pass now)";
    strUser = strarg;
    }
    else
    {
    strResponse = "400 user not found";
    }
    break;


    case "pass":
    if (users.ContainsKey(strUser) && users[strUser] == strarg)
    {
    strResponse = "200 authenticated";
    isAuthenticated = true;
    strOnlineUsers += strUser + " ";
    //-----------added--------------------------
    userWriter[strUser] = writer;
    //------------------------------------------


    }
    else
    {
    strResponse = "401 pass incorrect";
    }


    break;


    case "isauth":
    if (isAuthenticated)
    strResponse = "202 yes";
    else
    strResponse = "203 no";
    break;


    case "close":
    strOnlineUsers = strOnlineUsers.Replace(strUser + " ", "");
    strResponse = ("201 connection closed");
    //-----------added--------------------------
    userWriter.Remove(strUser);
    //------------------------------------------


    shouldBeListen = false;
    break;


    case "onusers":
    if (isAuthenticated)
    strResponse = "260 " + strOnlineUsers;
    else
    strResponse = "402 unauthenticated";
    break;
    //---------------added-------------
    case "tell":
    if (isAuthenticated)
    if (strOnlineUsers.IndexOf(strarg + " ") >= 0)
    {
    strResponse = "240 told";
    string strmsg="";
    for (int i = 3; i < strInputSegment.Length -1; i++)
    {
    strmsg += strInputSegment[i] + " ";
    }
    userWriter[strarg].WriteLine("250 " + strUser + " \" " + strmsg + " \"");
    userWriter[strarg].Flush();
    //dtMsg.Rows.Add(strUser,strarg,strmsg,false);
    }
    else
    strResponse = "403 "+strarg+" has gone";
    else
    strResponse = "402 unauthenticated";
    break;
    //----------------------------
    default:
    strResponse = "503 UnKnown Command";
    break;
    }
    writer.Write(strResponse + "\r\n");
    writer.Flush();
    }
    ns.Close();
    sok.Close();


    }


    }
    }




    فرم شیشم:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    //
    using System.Net.Sockets;
    using System.Threading;
    using System.Net;
    using System.IO;


    namespace winYahooServer
    {
    public partial class Form6 : Form
    {
    Dictionary<string, string> users;
    string strOnlineUsers = "";
    Dictionary<string, StreamWriter> userWriter = new Dictionary<string, StreamWriter>();


    public Form6()
    {
    //System.Diagnostics.Debugger.Launch();
    InitializeComponent();
    }


    private void Form6_Load(object sender, EventArgs e)
    {
    users = new Dictionary<string, string>();
    users["ali"] = "123";
    users["hasan"] = "123";
    users["akbar"] = "123";


    //InitDtMsg();


    Thread t = new Thread(new ThreadStart(Server));
    t.IsBackground = true;
    t.Start();


    }


    TcpListener listener;
    Socket s;


    private void Server()
    {


    IPAddress localip = IPAddress.Parse("127.0.0.1");


    listener = new TcpListener(localip, 8080);
    listener.Start();




    while (true)
    {
    s = listener.AcceptSocket();
    Thread t = new Thread(new ThreadStart(ListenIt));
    t.IsBackground = true;
    t.Start();


    }


    }


    private void ListenIt()
    {
    Socket sok = s;
    NetworkStream ns = new NetworkStream(sok);
    StreamWriter writer = new StreamWriter(ns);
    StreamReader reader = new StreamReader(ns);


    bool shouldBeListen = true;


    //for command recognition
    string strcommand = "", strarg = "";
    string strResponse = "";
    string[] strInputSegment;
    string str;


    //for saving user's info
    string strUser = "";
    bool isAuthenticated = false;


    while (shouldBeListen)
    {
    //may be error
    //need timer, session timeout=20
    str = "";
    try
    {
    str = reader.ReadLine();
    }
    catch
    {
    Thread.CurrentThread.Abort();
    }
    strInputSegment = str.Split(' ');
    try
    {
    strcommand = strInputSegment[0];
    }
    catch
    {
    strcommand = "error";
    }


    try
    {
    strarg = strInputSegment[1];
    }
    catch
    {
    strarg = "error";
    }


    switch (strcommand.ToLower())
    {
    case "user":
    if (users.ContainsKey(strarg))
    {
    strResponse = "300 user is ok (give pass now)";
    strUser = strarg;
    }
    else
    {
    strResponse = "400 user not found";
    }
    break;


    case "pass":
    if (users.ContainsKey(strUser) && users[strUser] == strarg)
    {
    strResponse = "200 authenticated";
    isAuthenticated = true;
    strOnlineUsers += strUser + " ";
    userWriter[strUser] = writer;


    }
    else
    {
    strResponse = "401 pass incorrect";
    }


    break;


    case "isauth":
    if (isAuthenticated)
    strResponse = "202 yes";
    else
    strResponse = "203 no";
    break;


    case "close":
    strOnlineUsers = strOnlineUsers.Replace(strUser + " ", "");
    strResponse = ("201 connection closed");
    userWriter.Remove(strUser);


    shouldBeListen = false;
    break;


    case "onusers":
    if (isAuthenticated)
    strResponse = "260 " + strOnlineUsers;
    else
    strResponse = "402 unauthenticated";
    break;
    case "tell":
    if (isAuthenticated)
    if (strOnlineUsers.IndexOf(strarg + " ") >= 0)
    {
    strResponse = "240 told";
    string strmsg = "";
    for (int i = 3; i < strInputSegment.Length - 1; i++)
    {
    strmsg += strInputSegment[i] + " ";
    }
    userWriter[strarg].WriteLine("250 " + strUser + " \" " + strmsg + " \"");
    userWriter[strarg].Flush();
    }
    else
    strResponse = "403 " + strarg + " has gone";
    else
    strResponse = "402 unauthenticated";
    break;
    //---------------added-------------
    case "adduser":
    try
    {
    if (isAuthenticated)
    strResponse = "405 you should log out first";
    else if (users.ContainsKey(strInputSegment[1]))
    strResponse = "404 user exsited";
    else
    {
    users.Add(strInputSegment[1], strInputSegment[2]);
    strResponse = "204 added";
    }
    }
    catch (Exception)
    {
    strResponse = "502 wrong arguments";
    }
    break;
    //----------------------------
    default:
    strResponse = "503 UnKnown Command";
    break;
    }
    writer.Write(strResponse + "\r\n");
    writer.Flush();
    }
    ns.Close();
    sok.Close();


    }


    }
    }




    فرم هفتم:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    //
    using System.Net.Sockets;
    using System.Threading;
    using System.Net;
    using System.IO;


    namespace winYahooServer
    {
    public partial class Form7 : Form
    {
    Dictionary<string, string> users;
    string strOnlineUsers = "";
    Dictionary<string, StreamWriter> userWriter = new Dictionary<string, StreamWriter>();


    public Form7()
    {
    //System.Diagnostics.Debugger.Launch();
    InitializeComponent();
    }


    private void Form7_Load(object sender, EventArgs e)
    {
    users = new Dictionary<string, string>();
    users["ali"] = "202cb962ac59075b964b07152d234b70";
    users["hasan"] = "202cb962ac59075b964b07152d234b70";
    users["akbar"] = "202cb962ac59075b964b07152d234b70";


    //InitDtMsg();


    Thread t = new Thread(new ThreadStart(Server));
    t.IsBackground = true;
    t.Start();


    }


    TcpListener listener;
    Socket s;


    private void Server()
    {


    IPAddress localip = IPAddress.Parse("127.0.0.1");


    listener = new TcpListener(localip, 8080);
    listener.Start();




    while (true)
    {
    s = listener.AcceptSocket();
    Thread t = new Thread(new ThreadStart(ListenIt));
    t.IsBackground = true;
    t.Start();


    }


    }


    private void ListenIt()
    {
    Socket sok = s;
    NetworkStream ns = new NetworkStream(sok);
    StreamWriter writer = new StreamWriter(ns);
    StreamReader reader = new StreamReader(ns);


    bool shouldBeListen = true;


    //for command recognition
    string strcommand = "", strarg = "";
    string strResponse = "";
    string[] strInputSegment;
    string str;


    //for saving user's info
    string strUser = "";
    bool isAuthenticated = false;


    while (shouldBeListen)
    {
    //may be error
    //need timer, session timeout=20
    str = "";
    try
    {
    str = reader.ReadLine();
    }
    catch
    {
    Thread.CurrentThread.Abort();
    }
    strInputSegment = str.Split(' ');
    try
    {
    strcommand = strInputSegment[0];
    }
    catch
    {
    strcommand = "error";
    }


    try
    {
    strarg = strInputSegment[1];
    }
    catch
    {
    strarg = "error";
    }


    switch (strcommand.ToLower())
    {
    case "user":
    if (users.ContainsKey(strarg))
    {
    strResponse = "300 user is ok (give pass now)";
    strUser = strarg;
    }
    else
    {
    strResponse = "400 user not found";
    }
    break;


    case "pass":
    string strHash= clsSecurity.ComputeMD5(strarg);
    if (users.ContainsKey(strUser) && users[strUser] == strHash)
    {
    strResponse = "200 authenticated";
    isAuthenticated = true;
    strOnlineUsers += strUser + " ";
    userWriter[strUser] = writer;


    }
    else
    {
    strResponse = "401 pass incorrect";
    }


    break;


    case "isauth":
    if (isAuthenticated)
    strResponse = "202 yes";
    else
    strResponse = "203 no";
    break;


    case "close":
    strOnlineUsers = strOnlineUsers.Replace(strUser + " ", "");
    strResponse = ("201 connection closed");
    userWriter.Remove(strUser);


    shouldBeListen = false;
    break;


    case "onusers":
    if (isAuthenticated)
    strResponse = "260 " + strOnlineUsers;
    else
    strResponse = "402 unauthenticated";
    break;
    case "tell":
    if (isAuthenticated)
    if (strOnlineUsers.IndexOf(strarg + " ") >= 0)
    {
    strResponse = "240 told";
    string strmsg = "";
    for (int i = 3; i < strInputSegment.Length - 1; i++)
    {
    strmsg += strInputSegment[i] + " ";
    }
    userWriter[strarg].WriteLine("250 " + strUser + " \" " + strmsg + " \"");
    userWriter[strarg].Flush();
    }
    else
    strResponse = "403 " + strarg + " has gone";
    else
    strResponse = "402 unauthenticated";
    break;
    //---------------updated-------------
    case "adduser":
    try
    {
    if (isAuthenticated)
    strResponse = "405 you should log out first";
    else if (users.ContainsKey(strInputSegment[1]))
    strResponse = "404 user exsited";
    else
    {
    users.Add(strInputSegment[1], clsSecurity.ComputeMD5(strInputSegment[2]));
    strResponse = "204 added";
    }
    }
    catch (Exception)
    {
    strResponse = "502 wrong arguments";
    }
    break;
    //----------------------------
    default:
    strResponse = "503 UnKnown Command";
    break;
    }
    writer.Write(strResponse + "\r\n");
    writer.Flush();
    }
    ns.Close();
    sok.Close();


    }


    }
    }




    فرم هشتم:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    //
    using System.Net.Sockets;
    using System.Threading;
    using System.Net;
    using System.IO;


    namespace winYahooServer
    {
    public partial class Form8 : Form
    {
    Dictionary<string, string> users;
    string strOnlineUsers = "";
    Dictionary<string, StreamWriter> userWriter = new Dictionary<string, StreamWriter>();
    //-------------------added--------------
    Dictionary<string, string> userKey = new Dictionary<string, string>();
    Dictionary<string, string> userIV = new Dictionary<string, string>();
    //--------------------------------------
    public Form8()
    {
    //System.Diagnostics.Debugger.Launch();
    InitializeComponent();
    }


    private void Form8_Load(object sender, EventArgs e)
    {
    users = new Dictionary<string, string>();
    users["ali"] = "202cb962ac59075b964b07152d234b70";
    users["hasan"] = "202cb962ac59075b964b07152d234b70";
    users["akbar"] = "202cb962ac59075b964b07152d234b70";




    Thread t = new Thread(new ThreadStart(Server));
    t.IsBackground = true;
    t.Start();


    }


    TcpListener listener;
    Socket s;


    private void Server()
    {


    IPAddress localip = IPAddress.Parse("127.0.0.1");


    listener = new TcpListener(localip, 8080);
    listener.Start();




    while (true)
    {
    s = listener.AcceptSocket();
    Thread t = new Thread(new ThreadStart(ListenIt));
    t.IsBackground = true;
    t.Start();


    }


    }


    private void ListenIt()
    {
    Socket sok = s;
    NetworkStream ns = new NetworkStream(sok);
    StreamWriter writer = new StreamWriter(ns);
    StreamReader reader = new StreamReader(ns);


    bool shouldBeListen = true;


    //for command recognition
    string strcommand = "", strarg = "";
    string strResponse = "";
    string[] strInputSegment;
    string str;


    //for saving user's info
    string strUser = "";
    bool isAuthenticated = false;
    //------------------added---------------
    string strKey = "", strIV = "";
    int isSecure = 0;
    //---------------------------------------
    while (shouldBeListen)
    {
    //may be error
    //need timer, session timeout=20
    str = "";
    try
    {
    str = reader.ReadLine();
    }
    catch
    {
    Thread.CurrentThread.Abort();
    }
    //-------------------------added---------------
    if (isSecure == 1)
    str = clsSecurity.DecryptAES(str, strKey, strIV);
    //----------------------------------------
    strInputSegment = str.Split(' ');
    try
    {
    strcommand = strInputSegment[0];
    }
    catch
    {
    strcommand = "error";
    }


    try
    {
    strarg = strInputSegment[1];
    }
    catch
    {
    strarg = "error";
    }


    switch (strcommand.ToLower())
    {
    case "user":
    if (users.ContainsKey(strarg))
    {
    strResponse = "300 user is ok (give pass now)";
    strUser = strarg;
    }
    else
    {
    strResponse = "400 user not found";
    }
    break;


    case "pass":
    string strHash = clsSecurity.ComputeMD5(strarg);
    if (users.ContainsKey(strUser) && users[strUser] == strHash)
    {
    strResponse = "200 authenticated";
    isAuthenticated = true;
    strOnlineUsers += strUser + " ";
    userWriter[strUser] = writer;
    //---------------------added---------------------
    if (isSecure == 1)
    {
    userKey[strUser] = strKey;
    userIV[strUser] = strIV;
    }
    //----------------------------------------------=
    }
    else
    {
    strResponse = "401 pass incorrect";
    }


    break;
    case "isauth":
    if (isAuthenticated)
    strResponse = "202 yes";
    else
    strResponse = "203 no";
    break;


    case "close":
    strOnlineUsers = strOnlineUsers.Replace(strUser + " ", "");
    strResponse = ("201 connection closed");
    userWriter.Remove(strUser);
    //---------------------added---------------
    if (isSecure == 1)
    {
    userKey.Remove(strUser);
    userIV.Remove(strUser);
    }
    //--------------------------------------
    shouldBeListen = false;
    break;


    case "onusers":
    if (isAuthenticated)
    strResponse = "260 " + strOnlineUsers;
    else
    strResponse = "402 unauthenticated";
    break;
    case "tell":
    if (isAuthenticated)
    if (strOnlineUsers.IndexOf(strarg + " ") >= 0)
    {
    strResponse = "240 told";
    string strmsg = "";
    for (int i = 3; i < strInputSegment.Length - 1; i++)
    {
    strmsg += strInputSegment[i] + " ";
    }
    //---------------------added-------------
    string strmessage = "250 " + strUser + " \" " + strmsg + " \"";
    if (userKey.ContainsKey(strarg))
    strmessage = clsSecurity.EncryptAES(strmessage, userKey[strarg], userIV[strarg]);
    //----------------------------------
    userWriter[strarg].WriteLine(strmessage);
    userWriter[strarg].Flush();
    }
    else
    strResponse = "403 " + strarg + " has gone";
    else
    strResponse = "402 unauthenticated";
    break;
    case "adduser":
    try
    {
    if (isAuthenticated)
    strResponse = "405 you should log out first";
    else if (users.ContainsKey(strInputSegment[1]))
    strResponse = "404 user exsited";
    else
    {
    users.Add(strInputSegment[1], clsSecurity.ComputeMD5(strInputSegment[2]));
    strResponse = "204 added";
    }
    }
    catch (Exception)
    {
    strResponse = "502 wrong arguments";
    }
    break;
    //--------------------added----------------
    case "secure":
    //strKey = "123456789abcdefg";
    strKey = clsSecurity.produceKey( 16, "SHA1", 5);
    strIV = clsSecurity.produceKey( 16, "SHA1", 1);
    strResponse="290 " + strKey + " " + strIV;
    isSecure = -1;
    break;
    //------------------------------------
    default:
    strResponse = "503 UnKnown Command";
    break;
    }
    if (isSecure == 1)
    strResponse = clsSecurity.EncryptAES(strResponse, strKey, strIV);
    else if (isSecure == -1)
    isSecure = 1;


    writer.Write(strResponse + "\r\n");
    writer.Flush();
    }
    ns.Close();
    sok.Close();


    }





    }
    }




    فرم آخر:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    //
    using System.Net.Sockets;
    using System.Threading;
    using System.Net;
    using System.IO;


    namespace winYahooServer
    {
    public partial class Form9 : Form
    {
    Dictionary<string, string> users;
    string strOnlineUsers = "";
    Dictionary<string, StreamWriter> userWriter = new Dictionary<string, StreamWriter>();
    Dictionary<string, string> userKey = new Dictionary<string, string>();
    Dictionary<string, string> userIV = new Dictionary<string, string>();
    //----------------------added------------
    string publickey, publicprivatekey;
    //------------------------------------
    public Form9()
    {
    //System.Diagnostics.Debugger.Launch();
    InitializeComponent();
    }


    private void Form9_Load(object sender, EventArgs e)
    {
    users = new Dictionary<string, string>();
    users["ali"] = "202cb962ac59075b964b07152d234b70";
    users["hasan"] = "202cb962ac59075b964b07152d234b70";
    users["akbar"] = "202cb962ac59075b964b07152d234b70";


    //----------------------added------------
    //در واقع اینها رو از کومودو می گیریم
    clsSecurity.getRSAkeys(out publickey, out publicprivatekey);
    //-------------------------------------
    Thread t = new Thread(new ThreadStart(Server));
    t.IsBackground = true;
    t.Start();


    }


    TcpListener listener;
    Socket s;


    private void Server()
    {


    IPAddress localip = IPAddress.Parse("127.0.0.1");


    listener = new TcpListener(localip, 8080);
    listener.Start();




    while (true)
    {
    s = listener.AcceptSocket();
    Thread t = new Thread(new ThreadStart(ListenIt));
    t.IsBackground = true;
    t.Start();


    }


    }


    private void ListenIt()
    {
    Socket sok = s;
    NetworkStream ns = new NetworkStream(sok);
    StreamWriter writer = new StreamWriter(ns);
    StreamReader reader = new StreamReader(ns);


    bool shouldBeListen = true;


    //for command recognition
    string strcommand = "", strarg = "";
    string strResponse = "";
    string[] strInputSegment;
    string str;


    //for saving user's info
    string strUser = "";
    bool isAuthenticated = false;
    string strKey = "", strIV = "";
    int isSecure = 0;
    while (shouldBeListen)
    {
    //may be error
    //need timer, session timeout=20
    str = "";
    try
    {
    str = reader.ReadLine();
    }
    catch
    {
    Thread.CurrentThread.Abort();
    }
    if (isSecure == 1)
    str = clsSecurity.DecryptAES(str, strKey, strIV);
    strInputSegment = str.Split(' ');
    try
    {
    strcommand = strInputSegment[0];
    }
    catch
    {
    strcommand = "error";
    }


    try
    {
    strarg = strInputSegment[1];
    }
    catch
    {
    strarg = "error";
    }


    switch (strcommand.ToLower())
    {
    case "user":
    if (users.ContainsKey(strarg))
    {
    strResponse = "300 user is ok (give pass now)";
    strUser = strarg;
    }
    else
    {
    strResponse = "400 user not found";
    }
    break;


    case "pass":
    string strHash = clsSecurity.ComputeMD5(strarg);
    if (users.ContainsKey(strUser) && users[strUser] == strHash)
    {
    strResponse = "200 authenticated";
    isAuthenticated = true;
    strOnlineUsers += strUser + " ";
    userWriter[strUser] = writer;
    if (isSecure == 1)
    {
    userKey[strUser] = strKey;
    userIV[strUser] = strIV;
    }
    }
    else
    {
    strResponse = "401 pass incorrect";
    }


    break;
    case "isauth":
    if (isAuthenticated)
    strResponse = "202 yes";
    else
    strResponse = "203 no";
    break;


    case "close":
    strOnlineUsers = strOnlineUsers.Replace(strUser + " ", "");
    strResponse = ("201 connection closed");
    userWriter.Remove(strUser);
    if (isSecure == 1)
    {
    userKey.Remove(strUser);
    userIV.Remove(strUser);
    }
    shouldBeListen = false;
    break;


    case "onusers":
    if (isAuthenticated)
    strResponse = "260 " + strOnlineUsers;
    else
    strResponse = "402 unauthenticated";
    break;
    case "tell":
    if (isAuthenticated)
    if (strOnlineUsers.IndexOf(strarg + " ") >= 0)
    {
    strResponse = "240 told";
    string strmsg = "";
    for (int i = 3; i < strInputSegment.Length - 1; i++)
    {
    strmsg += strInputSegment[i] + " ";
    }
    string strmessage = "250 " + strUser + " \" " + strmsg + " \"";
    if (userKey.ContainsKey(strarg))
    strmessage = clsSecurity.EncryptAES(strmessage, userKey[strarg], userIV[strarg]);
    userWriter[strarg].WriteLine(strmessage);
    userWriter[strarg].Flush();
    }
    else
    strResponse = "403 " + strarg + " has gone";
    else
    strResponse = "402 unauthenticated";
    break;
    case "adduser":
    try
    {
    if (isAuthenticated)
    strResponse = "405 you should log out first";
    else if (users.ContainsKey(strInputSegment[1]))
    strResponse = "404 user exsited";
    else
    {
    users.Add(strInputSegment[1], clsSecurity.ComputeMD5(strInputSegment[2]));
    strResponse = "204 added";
    }
    }
    catch (Exception)
    {
    strResponse = "502 wrong arguments";
    }
    break;
    case "secure":
    //strKey = "123456789abcdefg";
    strKey = clsSecurity.produceKey(16, "SHA1", 5);
    strIV = clsSecurity.produceKey(16, "SHA1", 1);
    strResponse = "290 " + strKey + " " + strIV;
    isSecure = -1;
    break;
    //----------------------added------------
    case "securessl":
    strResponse = "291 comodo.com " + publickey;
    break;
    case "securekey":
    strKey = clsSecurity.DecryptRSAwithPublicPrivateKey(publicprivatekey, strInputSegment[1]);
    strIV = clsSecurity.DecryptRSAwithPublicPrivateKey(publicprivatekey, strInputSegment[2]);
    isSecure = -1;
    strResponse = "292 ok";
    break;
    //----------------------added------------
    default:
    strResponse = "503 UnKnown Command";
    break;
    }
    if (isSecure == 1)
    strResponse = clsSecurity.EncryptAES(strResponse, strKey, strIV);
    else if (isSecure == -1)
    isSecure = 1;


    writer.Write(strResponse + "\r\n");
    writer.Flush();
    }
    ns.Close();
    sok.Close();


    }






    }
    }






    موفق باشید..

    موضوعات مشابه:
    فایل های پیوست شده
    • نوع فایل: zip winYahooServer.zip (132.6 کیلو بایت,  این فایل 9 بار دانلود شده است)
    ویرایش توسط Hossein : 4th July 2012 در ساعت 02:04 PM دلیل: لطفا توضیحات یادتون نره - زحمتی که میکشید رو با توضیحاتتون کامل کنید - مثلا اینجا کاربر که میاد نمیدونه چرا این
    آرامش محصول تفکر نیست! آرامش هنر نیندیشیدن به انبوه مسائلیست که ارزش فکر کردن ندارد...

  2. #2
    مدیر بازنشسته
    تاریخ عضویت
    2011 June
    محل سکونت
    گرگان
    ارسال ها
    1,170
    تشکر
    62
    تشکر شده 1,587 بار در 809 پست
    نوشته های وبلاگ
    49


    2 امتياز مثبت از 2 راي
    آيا اين پست براي شما سودمند بود؟ بله | خیر
    این باقی پست قبلیه!!!....

    کلاس موردنظر:

    using System;using System.Collections.Generic;
    //-----------------
    using System.Security.Cryptography;
    using System.Text;
    using System.IO;


    /// <summary>
    /// Summary description for clsSecurity
    /// </summary>
    public class clsSecurity
    {
    public clsSecurity()
    {
    }
    //.ToString("x2") returns hexadecimal format
    public static string ComputeMD5(string str)
    {
    string strResult = "";
    MD5 x = new MD5CryptoServiceProvider();
    byte[] bytesToHash = System.Text.Encoding.UTF8.GetBytes(str);
    bytesToHash = x.ComputeHash(bytesToHash);
    foreach (Byte b in bytesToHash)
    strResult += b.ToString("x2");
    return strResult;
    //return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");


    }


    public static string ComputeSHA1(string str)
    {
    string strResult = "";
    SHA1 x = new SHA1Managed();
    byte[] bytesToHash = System.Text.Encoding.UTF8.GetBytes(str);
    bytesToHash = x.ComputeHash(bytesToHash);
    foreach (Byte b in bytesToHash)
    strResult += b.ToString("x2");
    return strResult;
    //return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "SHA1");


    }


    public static void getRSAkeys(out string strPublicKey, out string strPublicPrivateKey)
    {
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    strPublicKey = rsa.ToXmlString(false);//public
    strPublicPrivateKey = rsa.ToXmlString(true);//public and private
    }


    //encrypt publicKey
    //decrypt public private key


    public static string EncryptRSAwithPublicKey(string strPublicKey, string strText)
    {
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    rsa.FromXmlString(strPublicKey);
    byte[] bs = rsa.Encrypt(Encoding.UTF8.GetBytes(strText), false);
    //ghalat kardi: return Encoding.UTF8.GetString(bs)
    return Convert.ToBase64String(bs);
    }
    public static string DecryptRSAwithPublicPrivateKey(string strPublicPrivateKey, string strEncrypted)
    {
    byte[] bs = Convert.FromBase64String(strEncrypted);
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    rsa.FromXmlString(strPublicPrivateKey);
    byte[] bs2 = rsa.Decrypt(bs, false);
    return Encoding.UTF8.GetString(bs2);
    }


    //signData public private key
    public static string SignWithRSA(string strPublicPrivateKey, string strText)
    {
    byte[] bs = UTF8Encoding.UTF8.GetBytes(strText);
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    rsa.FromXmlString(strPublicPrivateKey);
    byte[] bs2 = rsa.SignData(bs, new SHA1CryptoServiceProvider());
    //rsa.SignHash(bs);
    return Convert.ToBase64String(bs2);
    }


    public static bool VerifySignWithRSA(string strPublicKey, string strText, string strSign)
    {
    byte[] bsSign = Convert.FromBase64String(strSign);
    byte[] bsText= UTF8Encoding.UTF8.GetBytes(strText);
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    rsa.FromXmlString(strPublicKey);
    bool b=rsa.VerifyData(bsText, new SHA1CryptoServiceProvider(), bsSign);
    return b;
    }


    public static string EncryptAES(string plainText, string strKey, string strIV)
    {


    //byte[] Key = Encoding.ASCII.GetBytes(strKey);
    //byte[] IV = Encoding.ASCII.GetBytes(strIV);
    byte[] Key = Convert.FromBase64String(strKey);
    byte[] IV = Convert.FromBase64String(strIV);




    // Check arguments.
    if (plainText == null || plainText.Length <= 0)
    throw new ArgumentNullException("plainText");
    if (Key == null || Key.Length <= 0)
    throw new ArgumentNullException("Key");
    if (IV == null || IV.Length <= 0)
    throw new ArgumentNullException("Key");




    // Declare the streams used
    // to encrypt to an in memory
    // array of bytes.
    MemoryStream msEncrypt = null;
    CryptoStream csEncrypt = null;
    StreamWriter swEncrypt = null;


    // Declare the RijndaelManaged object
    // used to encrypt the data.
    RijndaelManaged aesAlg = null;
    // Declare the bytes used to hold the
    // encrypted data.
    byte[] encrypted = null;


    try
    {
    // Create a RijndaelManaged object
    // with the specified key and IV.
    aesAlg = new RijndaelManaged();
    aesAlg.Key = Key;
    aesAlg.IV = IV;


    // Create a decrytor to perform the stream transform.
    ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);


    // Create the streams used for encryption.
    msEncrypt = new MemoryStream();
    csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
    swEncrypt = new StreamWriter(csEncrypt);


    //csEncrypt.Write(byte[] ...)

    //Write all data to the stream.
    swEncrypt.Write(plainText);


    }
    finally
    {
    // Clean things up.


    // Close the streams.
    if (swEncrypt != null)
    swEncrypt.Close();
    if (csEncrypt != null)
    csEncrypt.Close();
    if (msEncrypt != null)
    msEncrypt.Close();


    // Clear the RijndaelManaged object.
    if (aesAlg != null)
    aesAlg.Clear();
    }


    // Return the encrypted bytes from the memory stream.
    return Convert.ToBase64String(msEncrypt.ToArray());


    }


    public static string DecryptAES(string str, string strKey, string strIV)
    {


    //byte[] Key = Encoding.ASCII.GetBytes(strKey);
    //byte[] IV = Encoding.ASCII.GetBytes(strIV);
    byte[] Key = Convert.FromBase64String(strKey);
    byte[] IV = Convert.FromBase64String(strIV);


    byte[] cipherText = Convert.FromBase64String(str);
    // Check arguments.
    if (cipherText == null || cipherText.Length <= 0)
    throw new ArgumentNullException("cipherText");
    if (Key == null || Key.Length <= 0)
    throw new ArgumentNullException("Key");
    if (IV == null || IV.Length <= 0)
    throw new ArgumentNullException("Key");




    // TDeclare the streams used
    // to decrypt to an in memory
    // array of bytes.
    MemoryStream msDecrypt = null;
    CryptoStream csDecrypt = null;
    StreamReader srDecrypt = null;


    // Declare the RijndaelManaged object
    // used to decrypt the data.
    RijndaelManaged aesAlg = null;
    // Declare the string used to hold
    // the decrypted text.
    string plaintext = null;


    try
    {
    // Create a RijndaelManaged object
    // with the specified key and IV.
    aesAlg = new RijndaelManaged();
    aesAlg.Key = Key;
    aesAlg.IV = IV;


    // Create a decrytor to perform the stream transform.
    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);


    // Create the streams used for decryption.
    msDecrypt = new MemoryStream(cipherText);
    csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
    srDecrypt = new StreamReader(csDecrypt);


    // Read the decrypted bytes from the decrypting stream
    // and place them in a string.
    plaintext = srDecrypt.ReadToEnd();
    }
    finally
    {
    // Clean things up.


    // Close the streams.
    if (srDecrypt != null)
    srDecrypt.Close();
    if (csDecrypt != null)
    csDecrypt.Close();
    if (msDecrypt != null)
    msDecrypt.Close();


    // Clear the RijndaelManaged object.
    if (aesAlg != null)
    aesAlg.Clear();
    }


    return plaintext;


    }


    public static string produceKey(string strPhrase, int keysize, string hashAlgorithm, int passwordIterations)
    {
    byte[] saltValueBytes = new byte[keysize];
    Random r=new Random();
    r.NextBytes(saltValueBytes);
    PasswordDeriveBytes password = new PasswordDeriveBytes(
    strPhrase,
    saltValueBytes,
    hashAlgorithm,
    passwordIterations);
    byte[] keyBytes = password.GetBytes(16);
    string str = Convert.ToBase64String(keyBytes);
    return str;//str.Substring(0, 16);
    }


    public static string produceKey(int keysize, string hashAlgorithm, int passwordIterations)
    {
    byte[] saltValueBytes = new byte[keysize];
    Random r = new Random();
    r.NextBytes(saltValueBytes);
    string strPhrase = r.NextDouble().ToString();
    PasswordDeriveBytes password = new PasswordDeriveBytes(
    strPhrase,
    saltValueBytes,
    hashAlgorithm,
    passwordIterations);
    byte[] keyBytes = password.GetBytes(keysize);
    string str = Convert.ToBase64String(keyBytes);
    return str; //.Substring(0, 16);
    }


    }




    فرم اول:

    using System;using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    //
    using System.Net.Sockets;
    using System.IO;
    using System.Threading;


    namespace winYahooClient
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }
    TcpClient tcp;
    NetworkStream ns;
    StreamWriter writer;
    StreamReader reader;




    private void button1_Click(object sender, EventArgs e)
    {
    try
    {
    tcp = new TcpClient("localhost", 8080);
    tcp.NoDelay = false;
    //tcp.ReceiveTimeout = 60000;
    tcp.ReceiveBufferSize = 25000;
    ns = tcp.GetStream();
    writer = new StreamWriter(ns);
    reader = new StreamReader(ns);




    //user ali
    string strCode,strStatus;
    WriteCommand("user " + txtUsername.Text.Trim());
    ReadResult(out strCode, out strStatus);
    if (strCode != "300")
    {
    MessageBox.Show("Wrong username");
    return;
    }


    //pass 123
    WriteCommand("pass " + txtPassword.Text.Trim());
    ReadResult(out strCode, out strStatus);
    if (strCode != "200")
    {
    MessageBox.Show("Wrong password");
    return;
    }


    lblusername.Text = txtUsername.Text;


    pnlSignIn.Visible= false;
    pnlSignOut.Visible = true;
    pnlChat.Enabled = true;


    }
    catch (Exception ex)
    {


    MessageBox.Show("Error in connecting");
    }






    //prepare for listening
    PrepareTxtTextForThreading();
    PrepareCboUsersForThreading();
    PreparetoolStripStatusLabel1ForThreading();
    PrepareSetSignOutForThreading();


    Thread t = new Thread(new ThreadStart(Listening));
    t.IsBackground = true;
    t.Start();


    RefreshUsers();


    }




    private void WriteCommand(string str)
    {
    writer.WriteLine(str);
    writer.Flush();
    }


    private void ReadResult(out string strCode, out string strStatus)
    {
    strCode=""; strStatus="";
    string str = reader.ReadLine();
    if (str != null)
    {
    int idx = str.IndexOf(' ');
    strCode = str.Substring(0, idx);
    strStatus = str.Substring(idx + 1);
    }
    }


    private void Form1_Load(object sender, EventArgs e)
    {
    lblusername.Text = "";
    }


    private void btnRefreshUsers_Click(object sender, EventArgs e)
    {
    RefreshUsers();
    }


    private void RefreshUsers()
    {
    //cboUsers.Items.Clear();
    //onusers
    WriteCommand("onusers");
    }


    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
    if (pnlSignOut.Visible)
    SignOut();
    }


    private void button3_Click(object sender, EventArgs e)
    {
    SignOut();
    }


    private void SignOut()
    {
    WriteCommand("close");


    }


    private void btnSend_Click(object sender, EventArgs e)
    {
    if (cboUsers.Text == "")
    {
    MessageBox.Show("choose a user");
    return;
    }
    if (txtText.Text.Trim() == "")
    {
    MessageBox.Show("write something to send");
    return;
    }


    textBox1.Text += "\r\n" + lblusername.Text + " (" + DateTime.Now.ToLongTimeString() + ")>> " + txtText.Text; ;
    string strcmd = "tell " + cboUsers.Text + " \" " + txtText.Text + " \"";
    WriteCommand(strcmd);
    //inja javab nadad textBox1.Text += "\r\n" + lblusername.Text + " (" + DateTime.Now.ToLongTimeString() + ")>> " + txtText.Text; ;
    txtText.Text = "";


    }


    private void Listening()
    {


    while (true)
    {
    string strCode, strStatus;
    ReadResult(out strCode, out strStatus);
    switch (strCode)
    {
    case "250": //sth to show to user
    int idx = strStatus.IndexOf(' ');
    string sfreind = strStatus.Substring(0, idx);
    string msg = strStatus.Substring(idx + 1).Replace("\"", "").Trim();
    string message = "\r\n" + sfreind + " (" + DateTime.Now.ToLongTimeString() + ")>> " + msg;
    //textBox1.Text += message;
    //SetTxtText(message);
    this.Invoke(dlgSetTxtText, new object[] { message });
    break;
    case "260": //onusers
    /*
    cboUsers.Items.Clear();
    string[] users = strStatus.Split(' ');
    foreach (string str in users)
    {
    cboUsers.Items.Add(str);
    }
    */
    this.Invoke(dlgSetCboUsers, new object[] { strStatus });
    break;


    case "201": //connection close
    this.Invoke(dlgSetSignOutInThreading);
    break;


    case "240": //msg is told
    case "403": //user is gone
    case "402": //user is not authenticated to see onusers
    this.Invoke(dlgSetToolStripStatusLabel1, new object[] { strStatus });
    break;


    default:
    string strmsg = "unknown code error (" + strCode + ") came from server";
    this.Invoke(dlgSetToolStripStatusLabel1, new object[] { strmsg });
    break;
    }




    }
    }






    # region DoSomething
    public delegate void DoSomething();
    public DoSomething dlgSetSignOutInThreading;
    private void SetForSignout()
    {
    lblusername.Text = "";


    pnlSignIn.Visible = true;
    pnlSignOut.Visible = false;
    pnlChat.Enabled = false;
    }
    //in form_Load
    private void PrepareSetSignOutForThreading()
    {
    dlgSetSignOutInThreading = new DoSomething(SetForSignout);
    }


    #endregion






    public delegate void SendMessage(string message);




    # region TxtText setting in thread


    public SendMessage dlgSetTxtText;
    private void SetTxtText(string message)
    {
    textBox1.Text += message;
    }
    //in form_Load
    private void PrepareTxtTextForThreading()
    {
    dlgSetTxtText = new SendMessage(SetTxtText);
    }
    # endregion


    # region cboUsers setting in thread


    public SendMessage dlgSetCboUsers;
    private void SetCboUsers(string strStatus)
    {
    cboUsers.Items.Clear();
    string[] users = strStatus.Split(' ');
    foreach (string str in users)
    {
    string str2 = str.Trim();
    if (str2 != "")
    cboUsers.Items.Add(str2);
    }


    }
    //in form_Load
    private void PrepareCboUsersForThreading()
    {
    dlgSetCboUsers= new SendMessage(SetCboUsers);
    }
    # endregion


    # region toolStripStatusLabel1 setting in thread


    public SendMessage dlgSetToolStripStatusLabel1;
    private void SettoolStripStatusLabel1(string message)
    {
    toolStripStatusLabel1.Text = message;
    }
    //in form_Load
    private void PreparetoolStripStatusLabel1ForThreading()
    {
    dlgSetToolStripStatusLabel1 = new SendMessage(SettoolStripStatusLabel1);
    }
    # endregion


    }
    }




    فرم دوم:

    using System;using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    //
    using System.Net.Sockets;
    using System.IO;
    using System.Threading;


    namespace winYahooClient
    {
    public partial class SecureForm2 : Form
    {
    public SecureForm2()
    {
    InitializeComponent();
    }
    TcpClient tcp;
    NetworkStream ns;
    StreamWriter writer;
    StreamReader reader;
    Thread t;
    //---------------------------added-----------------------------
    string strKey="", strIV="";
    int isSecure = 0;
    //--------------------------------------------------------
    private void button1_Click(object sender, EventArgs e)
    {
    try
    {
    //user ali
    string strCode, strStatus;
    WriteCommand("user " + txtUsername.Text.Trim());
    ReadResult(out strCode, out strStatus);
    if (strCode != "300")
    {
    MessageBox.Show("Wrong username");
    return;
    }


    //pass 123
    WriteCommand("pass " + txtPassword.Text.Trim());
    ReadResult(out strCode, out strStatus);
    if (strCode != "200")
    {
    MessageBox.Show("Wrong password");
    return;
    }


    lblusername.Text = txtUsername.Text;


    pnlSignIn.Visible = false;
    pnlSignOut.Visible = true;
    pnlChat.Enabled = true;


    }
    catch (Exception ex)
    {


    MessageBox.Show("Error in connecting");
    return;
    }






    //prepare for listening
    PrepareTxtTextForThreading();
    PrepareCboUsersForThreading();
    PreparetoolStripStatusLabel1ForThreading();
    PrepareSetSignOutForThreading();


    t = new Thread(new ThreadStart(Listening));
    t.IsBackground = true;
    t.Start();


    RefreshUsers();


    }




    private void WriteCommand(string str)
    {
    //---------------------------added-----------------------------
    if (isSecure == 1)
    str = clsSecurity.EncryptAES(str, strKey, strIV);
    //----------------------------------------------------------------
    writer.WriteLine(str);
    writer.Flush();
    }


    private void ReadResult(out string strCode, out string strStatus)
    {
    strCode = ""; strStatus = "";
    string str = reader.ReadLine();
    //---------------------------added-----------------------------
    if (isSecure == 1)
    str = clsSecurity.DecryptAES(str, strKey, strIV);
    //--------------------------------------------------------------
    if (str != null)
    {
    int idx = str.IndexOf(' ');
    strCode = str.Substring(0, idx);
    strStatus = str.Substring(idx + 1);
    }
    }


    private void SecureForm2_Load(object sender, EventArgs e)
    {
    lblusername.Text = "";
    }


    private void btnRefreshUsers_Click(object sender, EventArgs e)
    {
    RefreshUsers();
    }


    private void RefreshUsers()
    {
    cboUsers.Items.Clear();
    //onusers
    WriteCommand("onusers");
    }


    private void SecureForm2_FormClosing(object sender, FormClosingEventArgs e)
    {
    if (lblusername.Text != "")
    SignOut();
    }


    private void button3_Click(object sender, EventArgs e)
    {
    SignOut();
    }


    private void SignOut()
    {
    WriteCommand("close");
    }


    private void btnSend_Click(object sender, EventArgs e)
    {
    if (cboUsers.Text == "")
    {
    MessageBox.Show("choose a user");
    return;
    }
    if (txtText.Text.Trim() == "")
    {
    MessageBox.Show("write something to send");
    return;
    }


    textBox1.Text += "\r\n" + lblusername.Text + " (" + DateTime.Now.ToLongTimeString() + ")>> " + txtText.Text; ;
    string strcmd = "tell " + cboUsers.Text + " \" " + txtText.Text + " \"";
    WriteCommand(strcmd);
    //inja javab nadad textBox1.Text += "\r\n" + lblusername.Text + " (" + DateTime.Now.ToLongTimeString() + ")>> " + txtText.Text; ;
    txtText.Text = "";


    }


    private void Listening()
    {


    while (true)
    {
    string strCode, strStatus;
    ReadResult(out strCode, out strStatus);
    switch (strCode)
    {
    case "250": //sth to show to user
    int idx = strStatus.IndexOf(' ');
    string sfreind = strStatus.Substring(0, idx);
    string msg = strStatus.Substring(idx + 1).Replace("\"", "").Trim();
    string message = "\r\n" + sfreind + " (" + DateTime.Now.ToLongTimeString() + ")>> " + msg;
    //textBox1.Text += message;
    //SetTxtText(message);
    this.Invoke(dlgSetTxtText, new object[] { message });
    break;
    case "260": //onusers
    /*
    cboUsers.Items.Clear();
    string[] users = strStatus.Split(' ');
    foreach (string str in users)
    {
    cboUsers.Items.Add(str);
    }
    */
    this.Invoke(dlgSetCboUsers, new object[] { strStatus });
    break;


    case "201": //connection close
    this.Invoke(dlgSetSignOutInThreading);
    Thread.CurrentThread.Abort();
    break;


    case "240": //msg is told
    case "403": //user is gone
    case "402": //user is not authenticated to see onusers
    this.Invoke(dlgSetToolStripStatusLabel1, new object[] { strStatus });
    break;


    default:
    string strmsg = "unknown code error (" + strCode + ") came from server";
    this.Invoke(dlgSetToolStripStatusLabel1, new object[] { strmsg });
    break;
    }




    }
    }






    # region DoSomething
    public delegate void DoSomething();
    public DoSomething dlgSetSignOutInThreading;
    private void SetForSignout()
    {
    lblusername.Text = "";


    pnlSignIn.Visible = true;
    pnlSignOut.Visible = false;
    pnlChat.Enabled = false;


    pnlSignIn.Enabled = false;
    pnlConnect.Enabled = true;


    isSecure = 0;
    }
    //in form_Load
    private void PrepareSetSignOutForThreading()
    {
    dlgSetSignOutInThreading = new DoSomething(SetForSignout);
    }


    #endregion






    public delegate void SendMessage(string message);




    # region TxtText setting in thread


    public SendMessage dlgSetTxtText;
    private void SetTxtText(string message)
    {
    textBox1.Text += message;
    }
    //in form_Load
    private void PrepareTxtTextForThreading()
    {
    dlgSetTxtText = new SendMessage(SetTxtText);
    }
    # endregion


    # region cboUsers setting in thread


    public SendMessage dlgSetCboUsers;
    private void SetCboUsers(string strStatus)
    {
    cboUsers.Items.Clear();
    string[] users = strStatus.Split(' ');
    foreach (string str in users)
    {
    string str2 = str.Trim();
    if (str2 != "")
    cboUsers.Items.Add(str2);
    }


    }
    //in form_Load
    private void PrepareCboUsersForThreading()
    {
    dlgSetCboUsers = new SendMessage(SetCboUsers);
    }
    # endregion


    # region toolStripStatusLabel1 setting in thread


    public SendMessage dlgSetToolStripStatusLabel1;
    private void SettoolStripStatusLabel1(string message)
    {
    toolStripStatusLabel1.Text = message;
    }
    //in form_Load
    private void PreparetoolStripStatusLabel1ForThreading()
    {
    dlgSetToolStripStatusLabel1 = new SendMessage(SettoolStripStatusLabel1);
    }
    # endregion


    private void btnConnect_Click(object sender, EventArgs e)
    {
    try
    {
    tcp = new TcpClient("localhost", 8080);
    tcp.NoDelay = false;
    //tcp.ReceiveTimeout = 60000;
    tcp.ReceiveBufferSize = 25000;
    ns = tcp.GetStream();
    writer = new StreamWriter(ns);
    reader = new StreamReader(ns);


    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    return;
    }
    //---------------------------added-----------------------------
    if (chkSecure.Checked)
    {
    string strCode, strStatus;
    WriteCommand("secure");
    ReadResult(out strCode, out strStatus);
    if (strCode == "290")
    {
    isSecure = 1;
    string[] str = strStatus.Split(' ');
    strKey = str[0];
    strIV = str[1];
    }
    }
    //------------------------------------------------------
    pnlSignIn.Enabled = true;
    pnlConnect.Enabled = false;


    }


    }
    }




    فرم سوم:

    using System;using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    //
    using System.Net.Sockets;
    using System.IO;
    using System.Threading;


    namespace winYahooClient
    {
    public partial class SecureForm3 : Form
    {
    public SecureForm3()
    {
    InitializeComponent();
    }
    TcpClient tcp;
    NetworkStream ns;
    StreamWriter writer;
    StreamReader reader;
    Thread t;
    string strKey = "", strIV = "";
    int isSecure = 0;




    private void button1_Click(object sender, EventArgs e)
    {
    try
    {
    //user ali
    string strCode, strStatus;
    WriteCommand("user " + txtUsername.Text.Trim());
    ReadResult(out strCode, out strStatus);
    if (strCode != "300")
    {
    MessageBox.Show("Wrong username");
    return;
    }


    //pass 123
    WriteCommand("pass " + txtPassword.Text.Trim());
    ReadResult(out strCode, out strStatus);
    if (strCode != "200")
    {
    MessageBox.Show("Wrong password");
    return;
    }


    lblusername.Text = txtUsername.Text;


    pnlSignIn.Visible = false;
    pnlSignOut.Visible = true;
    pnlChat.Enabled = true;


    }
    catch (Exception ex)
    {


    MessageBox.Show("Error in connecting");
    return;
    }






    //prepare for listening
    PrepareTxtTextForThreading();
    PrepareCboUsersForThreading();
    PreparetoolStripStatusLabel1ForThreading();
    PrepareSetSignOutForThreading();


    t = new Thread(new ThreadStart(Listening));
    t.IsBackground = true;
    t.Start();


    RefreshUsers();


    }




    private void WriteCommand(string str)
    {
    if (isSecure == 1)
    str = clsSecurity.EncryptAES(str, strKey, strIV);
    writer.WriteLine(str);
    writer.Flush();
    }


    private void ReadResult(out string strCode, out string strStatus)
    {
    strCode = ""; strStatus = "";
    string str = reader.ReadLine();
    if (isSecure == 1)
    str = clsSecurity.DecryptAES(str, strKey, strIV);


    if (str != null)
    {
    int idx = str.IndexOf(' ');
    strCode = str.Substring(0, idx);
    strStatus = str.Substring(idx + 1);
    }
    }


    private void SecureForm3_Load(object sender, EventArgs e)
    {
    lblusername.Text = "";
    }


    private void btnRefreshUsers_Click(object sender, EventArgs e)
    {
    RefreshUsers();
    }


    private void RefreshUsers()
    {
    cboUsers.Items.Clear();
    //onusers
    WriteCommand("onusers");
    }


    private void SecureForm3_FormClosing(object sender, FormClosingEventArgs e)
    {
    if (lblusername.Text != "")
    SignOut();
    }


    private void button3_Click(object sender, EventArgs e)
    {
    SignOut();
    }


    private void SignOut()
    {
    WriteCommand("close");
    }


    private void btnSend_Click(object sender, EventArgs e)
    {
    if (cboUsers.Text == "")
    {
    MessageBox.Show("choose a user");
    return;
    }
    if (txtText.Text.Trim() == "")
    {
    MessageBox.Show("write something to send");
    return;
    }


    textBox1.Text += "\r\n" + lblusername.Text + " (" + DateTime.Now.ToLongTimeString() + ")>> " + txtText.Text; ;
    string strcmd = "tell " + cboUsers.Text + " \" " + txtText.Text + " \"";
    WriteCommand(strcmd);
    //inja javab nadad textBox1.Text += "\r\n" + lblusername.Text + " (" + DateTime.Now.ToLongTimeString() + ")>> " + txtText.Text; ;
    txtText.Text = "";


    }


    private void Listening()
    {


    while (true)
    {
    string strCode, strStatus;
    ReadResult(out strCode, out strStatus);
    switch (strCode)
    {
    case "250": //sth to show to user
    int idx = strStatus.IndexOf(' ');
    string sfreind = strStatus.Substring(0, idx);
    string msg = strStatus.Substring(idx + 1).Replace("\"", "").Trim();
    string message = "\r\n" + sfreind + " (" + DateTime.Now.ToLongTimeString() + ")>> " + msg;
    //textBox1.Text += message;
    //SetTxtText(message);
    this.Invoke(dlgSetTxtText, new object[] { message });
    break;
    case "260": //onusers
    /*
    cboUsers.Items.Clear();
    string[] users = strStatus.Split(' ');
    foreach (string str in users)
    {
    cboUsers.Items.Add(str);
    }
    */
    this.Invoke(dlgSetCboUsers, new object[] { strStatus });
    break;


    case "201": //connection close
    this.Invoke(dlgSetSignOutInThreading);
    Thread.CurrentThread.Abort();
    break;


    case "240": //msg is told
    case "403": //user is gone
    case "402": //user is not authenticated to see onusers
    this.Invoke(dlgSetToolStripStatusLabel1, new object[] { strStatus });
    break;


    default:
    string strmsg = "unknown code error (" + strCode + ") came from server";
    this.Invoke(dlgSetToolStripStatusLabel1, new object[] { strmsg });
    break;
    }




    }
    }






    # region DoSomething
    public delegate void DoSomething();
    public DoSomething dlgSetSignOutInThreading;
    private void SetForSignout()
    {
    lblusername.Text = "";


    pnlSignIn.Visible = true;
    pnlSignOut.Visible = false;
    pnlChat.Enabled = false;


    pnlSignIn.Enabled = false;
    pnlConnect.Enabled = true;


    isSecure = 0;
    }
    //in form_Load
    private void PrepareSetSignOutForThreading()
    {
    dlgSetSignOutInThreading = new DoSomething(SetForSignout);
    }


    #endregion






    public delegate void SendMessage(string message);




    # region TxtText setting in thread


    public SendMessage dlgSetTxtText;
    private void SetTxtText(string message)
    {
    textBox1.Text += message;
    }
    //in form_Load
    private void PrepareTxtTextForThreading()
    {
    dlgSetTxtText = new SendMessage(SetTxtText);
    }
    # endregion


    # region cboUsers setting in thread


    public SendMessage dlgSetCboUsers;
    private void SetCboUsers(string strStatus)
    {
    cboUsers.Items.Clear();
    string[] users = strStatus.Split(' ');
    foreach (string str in users)
    {
    string str2 = str.Trim();
    if (str2 != "")
    cboUsers.Items.Add(str2);
    }


    }
    //in form_Load
    private void PrepareCboUsersForThreading()
    {
    dlgSetCboUsers = new SendMessage(SetCboUsers);
    }
    # endregion


    # region toolStripStatusLabel1 setting in thread


    public SendMessage dlgSetToolStripStatusLabel1;
    private void SettoolStripStatusLabel1(string message)
    {
    toolStripStatusLabel1.Text = message;
    }
    //in form_Load
    private void PreparetoolStripStatusLabel1ForThreading()
    {
    dlgSetToolStripStatusLabel1 = new SendMessage(SettoolStripStatusLabel1);
    }
    # endregion


    private void btnConnect_Click(object sender, EventArgs e)
    {
    try
    {
    tcp = new TcpClient("localhost", 8080);
    tcp.NoDelay = false;
    //tcp.ReceiveTimeout = 60000;
    tcp.ReceiveBufferSize = 25000;
    ns = tcp.GetStream();
    writer = new StreamWriter(ns);
    reader = new StreamReader(ns);


    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message);
    return;
    }


    //--------------------------------added-------------------------------
    string publickey="";


    if (chkSecure.Checked)
    {
    string strCode, strStatus;
    WriteCommand("securessl");
    ReadResult(out strCode, out strStatus);
    if (strCode == "291")
    {
    string[] str= strStatus.Split(' ');
    //str[0] comodo.com
    //str[1] publickey
    publickey = str[1];
    }


    strKey = clsSecurity.produceKey(16, "SHA1", 5);
    strIV = clsSecurity.produceKey(16, "SHA1", 2);


    string strrsaKey=clsSecurity.EncryptRSAwithPublicKey(publickey,strKey);
    string strrsaIV = clsSecurity.EncryptRSAwithPublicKey(publickey, strIV);
    WriteCommand("securekey " + strrsaKey + " " + strrsaIV);
    ReadResult(out strCode, out strStatus);


    if (strCode == "292")
    {
    isSecure = 1;
    //string[] str = strStatus.Split(' ');
    //strKey = str[0];
    //strIV = str[1];
    }


    }


    pnlSignIn.Enabled = true;
    pnlConnect.Enabled = false;


    }


    }
    }




    http://upload.ustmb.ir/uploads/winYahooClient.zip

    موفق باشید.

    آرامش محصول تفکر نیست! آرامش هنر نیندیشیدن به انبوه مسائلیست که ارزش فکر کردن ندارد...

  3. #3
    عضو تازه وارد
    تاریخ عضویت
    2012 June
    محل سکونت
    کنار دریای شمال
    ارسال ها
    10
    تشکر
    62
    تشکر شده 33 بار در 9 پست


    آيا اين پست براي شما سودمند بود؟ بله | خیر
    میخواستم اگه امکان داره لطف کنید و توضیحات مربوط به هر فرم و همینطور مربوط به هر تابع رو بذارید. اینکه در حالت کلی کارشون چیه.
    متشکرم


  4. #4
    مدیر بازنشسته
    تاریخ عضویت
    2011 June
    محل سکونت
    گرگان
    ارسال ها
    1,170
    تشکر
    62
    تشکر شده 1,587 بار در 809 پست
    نوشته های وبلاگ
    49


    آيا اين پست براي شما سودمند بود؟ بله | خیر
    دوست گلم متاسفم!! .... من کامل قادر به توضیحش نیستم ... پیشنهاد میکنم از آقای حسنپور (master) یا آقای قبادی (mehdi )سوال بفرمایین
    موفق باشی ..

    آرامش محصول تفکر نیست! آرامش هنر نیندیشیدن به انبوه مسائلیست که ارزش فکر کردن ندارد...

  5. #5
    بنیانگذار
    تاریخ عضویت
    2010 January
    محل سکونت
    زیر سایه خدا
    سن
    37
    ارسال ها
    1,308
    تشکر
    2,923
    تشکر شده 2,205 بار در 886 پست
    نوشته های وبلاگ
    37


    آيا اين پست براي شما سودمند بود؟ بله | خیر
    نقل قول نوشته اصلی توسط forough نمایش پست ها
    میخواستم اگه امکان داره لطف کنید و توضیحات مربوط به هر فرم و همینطور مربوط به هر تابع رو بذارید. اینکه در حالت کلی کارشون چیه.
    متشکرم
    من ایشالله فرصت کردم این اطلاعات رو به پست ایشون اضافه میکنم

    توکل بخدا
    http://DeepLearning.ir
    اولین و تنها مرجع یادگیری عمیق ایران


    هرکس از ظن خود شد یار من
    از درون من نجست اسرار من




  6. #6
    عضو تازه وارد
    تاریخ عضویت
    2012 June
    محل سکونت
    کنار دریای شمال
    ارسال ها
    10
    تشکر
    62
    تشکر شده 33 بار در 9 پست


    آيا اين پست براي شما سودمند بود؟ بله | خیر
    من توضیح توابعی که آشنا هستم تا اندازه ای که می دونم میذارم تا ایشاله کار بقیه دوستان سبک تر بشه. کلاس clssecurity برای تامین اهداف امنیتی در نظر گرفته شده. مثل سری موندن اطلاعات، احراز هویت کاربران، غیر قابل انکار بودن پیام ها و نظارت بر صحت اطلاعات. این کار با رمز نگاری انجام میشه و در کنار اون از درهمسازی یا هشینگ استفاده میشه. دو نوع الگوریتم رمز نگاری وجود داره شامل متقارن و نامتقارن. در رمزنگاری متقارن تنها از یک کلید یعنی کلید خصوصی که تنها بین فرستنده و گیرنده رد و بدل میشه استفاده میشه. و در رمزنگاری نامتقارن هر فرد دو کلید عمومی و خصوصی داره که کلید عمومی همه افراد در اختیار دیگران قرار داره اما کلید خصوصی مختص خود فرد هست و دیگران از اون آگاهی ندارن.در رمز نگاری نا متقارن امکان استفاده از امضای دیجیتال هم وجود داره.به عنوان مثال رد و بدل کردن اطلاعات بین دو فرد "الف" و "ب" با این شیوه، به این شکله که ابتدا فرد "الف" با کلید خصوصی خودش متن رو و یا خلاصه ای از متن درهمسازی (هش) شده رو امضا می کنه و بعد با کلید عمومی فرد "ب" متن اصلی رو رمز می کنه و بعد متن رمز شده و متن امضا شده رو در قالب یک پیغام ارسال می کنه. فرد "ب" با دریافت پیام اول با کلید خصوصی خودش متن رو از حالت رمز در میاره و بعد با کلید عمومی شخص "الف" صحت امضا رو چک می کنه. در واقع امضای دیجیتال تایید می کنه که محتوای پیغام دستکاری نشده. در حالت کلی رمزنگاری سری بودن اطلاعات رو تضمین می کنه و اگه همراه با امضای دیجیتال باشه در کنار سری بودن، صحت و غیر قابل انکار بودن اطلاعات هم چک میشه. این بحث خیلی مفصله و به نظر من یه تاپیک جدا می طلبه. البته فصل 8 کتاب شبکه های کامپیوتری تنن بام با عنوان امنیت مفصل و جامع در این مورد توضیح داده. فکر می کنم این اندازه توضیح به عنوان مقدمه این بخش کافی باشه . برای درهمسازی از دو نمونه از توابع MD5 و SHA1 استفاده میشه و برای رمزنگاری نامتقارن از RSA . حالا در ارتباط با توابع این کلاس: توابع computeMD5 و computeSHA1 برای درهمسازی استفاده میشن یعنی یک متن رو به صورت رشته دریافت و یک متن درهمریخته رو به صورت رشته بر می گردونن. با ذکر این نکته که این متن درهمسازی شده دیگه قابل برگشت نیست. این تابع به عنوان مثال برای هش کردن پسوورد مناسبه. تابع getRSAkeys برای تولید کلید های خصوصی و عمومیه.خروجی اون یک کلید عمومی و یک کلید عمومی_خصوصیه. که کاربر بعد از دریافت، اون رو روی یه فایل متنی ذخیره می کنه و در مواقع لزوم از اون استفاده می کنه. تابع EncryptRSAwithPublickey برای رمزنگاری با کلید عمومی به کار میره که مورد کاربردش گفته شد. این تابع کلید عمومی و متن اصلی رو دریافت و متن رمز شده رو بر می گردونه. تابع DecryptRSAwithPublicPrivatekey با دریافت کلید عمومی _خصوصی و متن رمز شده متن اصلی رو بر می گردونه. در واقع متن رو از رمز در میاره. تابع SignwithRSA هم برای امضای دیجیتال کاربرد داره که با دریافت کلید عمومی _ خصوصی و متن (که می تونیم قبلش اونو با توابع گفته شده هش کنیم) متن امضا شده رو بر می گردونه. تابع VeryfywithRSA با در یافت کلید عمومی و متن اصلی (که قبلا توسط گیرنده از رمز دراومده) و متن امضا شده صحت امضای فرستنده رو چک می کنه. خروجی اون یک مقدار بولینه . تابع EncryptAES برای رمز نگاری به صورت متقارن استفاده میشه که متن اصلی، کلید و یک عدد تصادفی 16 تایی رو به عنوان ورودی دریافت و متن رمز شده رو بر میگردونه و تابع DecryptAES برای رمزگشایی متقارن به کار میره به این شکل که متن رمز شده، کلید و یک عدد تصادفی 16 تایی رو میگیره و متن اصلی رو برمی گردونه. امیدوارم توضیحاتم مفید واقع بشه.


 

 

کاربران برچسب خورده در این موضوع

کلمات کلیدی این موضوع

علاقه مندی ها (Bookmarks)

علاقه مندی ها (Bookmarks)

مجوز های ارسال و ویرایش

  • شما نمیتوانید موضوع جدیدی ارسال کنید
  • شما امکان ارسال پاسخ را ندارید
  • شما نمیتوانید فایل پیوست کنید.
  • شما نمیتوانید پست های خود را ویرایش کنید
  •  


Powered by vBulletin
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO 3.6.0
Persian Language By Ustmb.ir
این انجمن کاملا مستقل بوده و هیچ ارتباطی با دانشگاه علوم و فنون مازندران و مسئولان آن ندارد..این انجمن و تمامی محتوای تولید شده در آن توسط دانشجویان فعلی و فارغ التحصیل ادوار گذشته این دانشگاه برای استفاده دانشجویان جدید این دانشگاه و جامعه دانشگاهی کشور فراهم شده است.لطفا برای اطلاعات بیشتر در رابطه با ماهیت انجمن با مدیریت انجمن ارتباط برقرار کنید
ساعت 05:57 AM بر حسب GMT +4 می باشد.