实例介绍
【实例截图】

【核心代码】
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Security;
using System.Security.Cryptography;
namespace PKI2
{
public partial class Form1 : Form
{
//用户定义
private bool isconnecting = false;
private bool isconnected = false;
private bool isclient = false;
private const string infDisconn = "#DISCONNECT#";
//接受信息线程
private Thread th;
//监听连接信号线程
private Thread wait;
private setPortForm portform;
private madecer Makecert;
private EnDES endes;
private DeDES dedes;
static public TcpListener tcp1;
static public int port;
//客户端
private TcpClient tcpc;
//服务器端
private TcpClient tcps;
//客户端
private NetworkStream nsc;
//服务器端
OpenFileDialog of;
private NetworkStream nss;
private NetworkStream nswc;
private NetworkStream nsws;
private string _filePathName = string.Empty; //文件名
private string _destination = string.Empty; //目标文件名
static public string Deskeymi;
static public string Deskeyming;
public Form1()
{
InitializeComponent();
}
private void button_connect_Click(object sender, EventArgs e)
{
if (this.youip.Text.Length == 0 || this.textBox2.Text.Length == 1)
{
string str = "请输入正确的IP地址和端口号";
string cmd = "错误";
MessageBox.Show(str, cmd);
return;
}
tcpc = new TcpClient();
string ip = this.youip.Text;
int pnum = System.Convert.ToInt32(this.textBox2.Text, 10);
try
{
tcpc.Connect(IPAddress.Parse(ip), pnum);
}
catch (ArgumentOutOfRangeException)
{
string str = "请输入有效的端口号";
string cmd = "错误";
MessageBox.Show(str, cmd);
return;
}
catch (SocketException)
{
string str = "找不到对方,请重新确认对方的网络参数";
string cmd = "错误";
MessageBox.Show(str, cmd);
return;
}
//获取网络流
nsc = tcpc.GetStream();
//保存到读取数据的数组
byte[] read = new byte[2];
//读取字节数
int bytes = nsc.Read(read, 0, read.Length);
//根据读到的字节数来判断对方作出何种回应,1表示允许连接,2表示拒绝
if (bytes == 1)
{
string str = "已经建立连接!";
string cmd = "完成";
MessageBox.Show(str, cmd);
isconnecting = true;
isconnected = true;
isclient = true;
//创建接受信息线程
th = new Thread(new ThreadStart(acceptmsg));
th.Start();
}
}
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
portform=new setPortForm();
portform.ShowDialog();
this.Text="c/s通信";
//启动tcplistner
tcp1.Start();
//启动等待连接线程
wait=new Thread(new ThreadStart(waitconn));
wait.Start();
}
private void waitconn()
{
//开始监听本地连接端口
tcps = tcp1.AcceptTcpClient();
nss = tcps.GetStream();
//弹出连接对话筐
string str = "用户请求连接,接受?";
string cmd = "连接请求";
/// this.Text = "P2P聊天(会话进行中)";
DialogResult diares = MessageBox.Show(str, cmd, MessageBoxButtons.YesNo);
//处理回应2个中间变量
string strresp;
byte[] byteresp;
if (diares == DialogResult.Yes)
{
strresp = "#";
byteresp = System.Text.Encoding.ASCII.GetBytes(strresp.ToCharArray());
//将数据写入流
nss.Write(byteresp, 0, byteresp.Length);
//改变控制变量
isconnecting = true;
isconnected = true;
isclient = false;
//启动接受信息线程
th = new Thread(new ThreadStart(acceptmsg));
th.Start();
}
else if (diares == DialogResult.No)
{
strresp = "##";
byteresp = System.Text.Encoding.ASCII.GetBytes(strresp.ToCharArray());
nss.Write(byteresp, 0, byteresp.Length);
nss.Close();
tcps.Close();
disconnect();
}
}
private void disconnect()
{
isconnecting = false;
//启动等待连接线程
wait = new Thread(new ThreadStart(waitconn));
wait.Start();
}
private void disconnect(TcpClient tcpc, NetworkStream ns)
{
byte[] write = new byte[64];
write = System.Text.Encoding.ASCII.GetBytes(infDisconn.ToCharArray());
ns.Write(write, 0, write.Length);
ns.Close();
tcpc.Close();
disconnect();
}
//重载函数
protected override void OnClosed(EventArgs e)
{
if (isconnecting)
{
if (isclient)
{
disconnect(tcpc, nsc);
}
else
{
disconnect(tcps, nss);
}
}
tcp1.Stop();
wait.Abort();
}
private void acceptmsg()
{
while (isconnecting)
{
if (isclient)
{
acceptmsg(tcpc, nsc);
}
else
{
acceptmsg(tcps, nss);
}
}
}
private void acceptmsg(TcpClient tcpc, NetworkStream ns)
{
byte[] read = new byte[1024];
byte[]fl=new byte[1];
ns = tcpc.GetStream();
ns.Read(fl, 0, fl.Length);
string flag = System.Text.Encoding.ASCII.GetString(fl.ToArray());
if (string.Compare(flag, "%") != 0)
{ string strout=flag;
ns.Read(read, 0, read.Length);
strout = System.Text.Encoding.ASCII.GetString(read.ToArray());
if (string.Compare(strout, infDisconn) == 0)
{
string str = "用户已经断开了连接";
string cmd = "连接已断开";
MessageBox.Show(str, cmd);
this.richTextBox1.AppendText(str "\n");
this.Text = "c/s通信";
ns.Close();
tcpc.Close();
disconnect();
}
else
{
this.Text = "c/s通信";
this.richTextBox1.AppendText(strout);
this.richTextBox1.AppendText("\n");
}
}
else
{
string path = this.textBox3.Text.Trim();
string strout;
ns.Read(read, 0, read.Length);
strout= System.Text.Encoding.ASCII.GetString(read.ToArray());
File.WriteAllText(path, strout);
}
}
private void button_sendmesg_Click(object sender, EventArgs e)
{
if (isclient)
{
sendmsg(nsc);
}
else
{
sendmsg(nss);
}
}
private void sendmsg(NetworkStream ns)
{
string msg =this.richTextBox2.Text;
this.richTextBox2.Text = null;
byte[] write = new byte[1024];
write = System.Text.Encoding.ASCII.GetBytes(msg);
ns.Write(write, 0, write.Length);
this.richTextBox2.Focus();
}
private void button1_Click(object sender, EventArgs e)
{
this.richTextBox1.Clear();
this.richTextBox2.Clear();
}
//文件发送
private void button2_Click(object sender, EventArgs e)
{
//string path = this.textBox_wen.Text.Trim();
FileStream fs = new FileStream(of.FileName, FileMode.Open);
nswc=tcpc.GetStream();
int sendcount=0;
string flag = "%";
long leni;
string lens;
byte[] countbuffer = new byte[1];
byte[] len= new byte[1];
byte[] clientbuffer=new byte[1024];
countbuffer = System.Text.Encoding.ASCII.GetBytes(flag.ToCharArray());
leni = fs.Length;
lens = leni.ToString();
//len= System.Text.Encoding.ASCII.GetBytes(lens.ToCharArray());
this.nswc.Write(countbuffer, 0, 1);
//this.nswc.Write(len,0, 1,);
while(sendcount<fs.Length&&nswc.CanWrite)
{
int count=fs.Read(clientbuffer,0,clientbuffer.Length);
this.nswc.Write(clientbuffer,0,count);
sendcount= count;
}
nswc.Close();
fs.Close();
}
//文件加密
private void button6_Click(object sender, EventArgs e)
{
try
{
Encryptor encryptor = new Encryptor();
encryptor.Key = GetPassword();
encryptor.EncryptFile(_filePathName, _destination);
MessageBox.Show("Succeed !");
}
catch (Exception exp)
{
MessageBox.Show(exp.Message, "加密");
}
}
//获取密码
private string GetPassword()
{
string psword = textBoxDkey.Text;
if (8 > psword.Length)
{
return psword.PadRight(8, 's');
}
else if (8 < psword.Length)
{
return psword.Substring(0, 8);
}
return psword;
}
//文件选择
private void button7_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "file (*.*)|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
_filePathName = dlg.FileName;
textBox_wen.Text = _filePathName;
}
private void button6_Click_1(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "file (*.*)|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
_destination = dlg.FileName; ;
textBox_de.Text = _destination;
}
#region 目标文件
//设置目标文件文本框
private void SetDestination()
{
}
#endregion
private void button_jie_Click(object sender, EventArgs e)
{
try
{
Encryptor descryptor = new Encryptor();
descryptor.Key = GetPassword();
descryptor.DecryptFile(_filePathName, _destination);
MessageBox.Show("Succeed !");
}
catch (Exception exp)
{
MessageBox.Show(exp.Message, "解密");
}
}
class Encryptor
{
//字段
private string iv = string.Empty;
private string key = string.Empty;
#region 属性
/// <summary>
/// DES加密偏移量,必须是>=8位长的字符串
/// </summary>
public string IV
{
get { return iv; }
set { iv = value; }
}
/// <summary>
/// DES加密的私钥,必须是8位长的字符串
/// </summary>
public string Key
{
get { return key; }
set { key = value; }
}
#endregion
// string -> byte[]
private byte[] GetBytes(string str)
{
return Encoding.ASCII.GetBytes(str);
}
// 生成加解密工具 ( true加密, false解密 )
private ICryptoTransform CreateTransformer(bool encrypt_Decrypt)
{
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
des.Key = GetBytes(key); //key必须是8byte 64位
if (string.Empty == iv)
iv = key;
des.IV = GetBytes(iv);
if (encrypt_Decrypt)
return des.CreateEncryptor();
else
return des.CreateDecryptor();
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
return null;
}
}
// 对字符串进行DES加密
/// <summary>
/// 对字符串进行DES加密
/// </summary>
/// <param name="sourceString">待加密的字符串</param>
/// <returns>加密后的BASE64编码的字符串</returns>
public string Encrypt(string sourceString)
{
using (MemoryStream ms = new MemoryStream())
{
byte[] inData = GetBytes(sourceString);
try
{
ICryptoTransform transformer = CreateTransformer(true);
if (null == transformer) return null;
using (CryptoStream cs = new CryptoStream(ms, transformer, CryptoStreamMode.Write))
{
cs.Write(inData, 0, inData.Length);
cs.FlushFinalBlock();
}
return Convert.ToBase64String(ms.ToArray());
}
catch
{
throw;
}
}
}
// 对DES加密后的字符串进行解密
/// <summary>
/// 对DES加密后的字符串进行解密
/// </summary>
/// <param name="encryptedString">待解密的字符串</param>
/// <returns>解密后的字符串</returns>
public string Decrypt(string encryptedString)
{
using (MemoryStream ms = new MemoryStream())
{
byte[] inData = Convert.FromBase64String(encryptedString);
try
{
ICryptoTransform transformer = CreateTransformer(false);
if (null == transformer) return null;
using (CryptoStream cs = new CryptoStream(ms, transformer, CryptoStreamMode.Write))
{
cs.Write(inData, 0, inData.Length);
cs.FlushFinalBlock();
}
return UnicodeEncoding.Unicode.GetString(ms.ToArray());
}
catch
{
throw;
}
}
}
//对文件进行加解密
private void TransformFile(string sourceFile, string destFile, bool encrypt_Decrypt)
{
if (!File.Exists(sourceFile))
throw new FileNotFoundException("指定的文件路径不存在!", sourceFile);
byte[] btFile = File.ReadAllBytes(sourceFile);
using (FileStream fs = new FileStream(destFile, FileMode.Create, FileAccess.Write))
{
try
{
ICryptoTransform transformer = CreateTransformer(encrypt_Decrypt);
if (null == transformer) return;
using (CryptoStream cs = new CryptoStream(fs, transformer, CryptoStreamMode.Write))
{
cs.Write(btFile, 0, btFile.Length);
cs.FlushFinalBlock();
}
}
catch (CryptographicException)
{
throw new Exception("密码不正确");
}
catch
{
throw;
}
finally
{
fs.Close();
}
}
}
/// <summary>
/// 对文件内容进行DES加密
/// </summary>
/// <param name="sourceFile">待加密的文件绝对路径</param>
/// <param name="destFile">加密后的文件保存的绝对路径</param>
public void EncryptFile(string sourceFile, string destFile)
{
TransformFile(sourceFile, destFile, true);
}
/// <summary>
/// 对文件内容进行DES加密,加密后覆盖掉原来的文件
/// </summary>
/// <param name="sourceFile">待加密的文件的绝对路径</param>
public void EncryptFile(string sourceFile)
{
EncryptFile(sourceFile, sourceFile);
}
/// <summary>
/// 对文件内容进行DES解密
/// </summary>
/// <param name="sourceFile">待解密的文件绝对路径</param>
/// <param name="destFile">解密后的文件保存的绝对路径</param>
public void DecryptFile(string sourceFile, string destFile)
{
TransformFile(sourceFile, destFile, false);
}
/// <summary>
/// 对文件内容进行DES解密,加密后覆盖掉原来的文件
/// </summary>
/// <param name="sourceFile">待解密的文件的绝对路径</param>
public void DecryptFile(string sourceFile)
{
DecryptFile(sourceFile, sourceFile);
}
}
private void button5_Click(object sender, EventArgs e)
{
Makecert = new madecer();
Makecert.ShowDialog();
}
private void button4_Click(object sender, EventArgs e)
{
endes= new EnDES();
endes.ShowDialog();
}
private void button3_Click(object sender, EventArgs e)
{
dedes = new DeDES();
dedes.ShowDialog();
}
private void button8_Click(object sender, EventArgs e)
{
richTextBox2.Text = Deskeymi;
}
private void button9_Click(object sender, EventArgs e)
{
of = new OpenFileDialog();
if (of.ShowDialog() == DialogResult.OK)
{
textBox1.Text = of.FileName;
}
}
private void button_disconnect_Click(object sender, EventArgs e)
{
if (isclient)
{
disconnect(tcpc, nsc);
}
else
{
disconnect(tcps, nss);
}
}
private void 接受信息_Click(object sender, EventArgs e)
{
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void groupBox3_Enter(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void youip_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
}
}
标签: 编程
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


网友评论
我要评论