实例介绍
【实例简介】
实践的加解密文件例子,附带传输,可签名验证
很有借鉴作用
【实例截图】
【核心代码】
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;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using DESHelp;
using TransferFilesHelper;
using System.Threading;
using System.IO;
namespace ServerSide
{
public partial class ServerMain : Form
{
string strMD5 = string.Empty; //文件的MD5值,用于检验客户端发过来的文件
Thread threadListener;
delegate void SetTextBoxValue(string strPath); //设置richTextbox值的委托
public ServerMain()
{
InitializeComponent();
this.toolStripStatusLabelServerMain.Text = "加载完毕";
}
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);
private int GetConnectedState()
{
int INTERNET_CONNECTION_MODEM = 1;
int INTERNET_CONNECTION_LAN = 2;
int INTERNET_CONNECTION_PROXY = 4;
int INTERNET_CONNECTION_MODEM_BUSY = 8;
int flags = 0;
/* connectionType变量内容
* 11(在线:拨号上网)
* 12(在线:通过局域网)
* 13(在线:代理)
* 14(MODEM被其他非INTERNET连接占用)
*/
int connectionType=-1;
#region 获取网络连接状态
bool state = InternetGetConnectedState(out flags, 0);
if (state)
{
if ((flags & INTERNET_CONNECTION_MODEM) == INTERNET_CONNECTION_MODEM)
{
connectionType = 11;
}
if ((flags & INTERNET_CONNECTION_LAN) == INTERNET_CONNECTION_LAN)
{
connectionType = 12;
}
if ((flags & INTERNET_CONNECTION_PROXY) == INTERNET_CONNECTION_PROXY)
{
connectionType = 13;
}
if ((flags & INTERNET_CONNECTION_MODEM_BUSY) == INTERNET_CONNECTION_MODEM_BUSY)
{
connectionType = 14;
}
}
#endregion
return connectionType;
}
private void SetRichTextBoxValue(string strPath)
{
if (this.richTextBoxValue.InvokeRequired) //控件是否跨线程
{
SetTextBoxValue setValue = new SetTextBoxValue(SetRichTextBoxValue);
this.richTextBoxValue.Invoke(setValue, strPath);
}
else
{
this.richTextBoxValue.LoadFile(strPath, RichTextBoxStreamType.PlainText);
this.richTextBoxValue.Update();
}
}
private void buttonMonitor_Click(object sender, EventArgs e)
{
threadListener = new Thread(new ThreadStart(this.StartingReceive));
threadListener.Start(); //启动监听线程
}
private void StartingReceive()
{
try
{
int intPort = Convert.ToInt32(this.textBoxPort.Text); //本机开设的端口号
string strIPAddress = string.Empty; //本机IP地址
/* 网络连接标志解释
* 11(在线:拨号上网)
* 12(在线:通过局域网)
* 13(在线:代理)
* 14(MODEM被其他非INTERNET连接占用)
*/
int connectionState = this.GetConnectedState();
#region 判断网络连接的类型
if (11 == connectionState)
{
IPAddress[] ipAddresses = this.GetLocalIPAddresses();
int countIPAddresses = ipAddresses.Length;
strIPAddress = ipAddresses[countIPAddresses / 2].ToString();
}
else if (12 == connectionState)
{
IPAddress[] ipAddresses = this.GetLocalIPAddresses();
int countIPAddresses = ipAddresses.Length;
strIPAddress = ipAddresses[countIPAddresses / 2].ToString();
}
else
{
MessageBox.Show("该模块暂时未处理,请联系开发人", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
#endregion
if (strIPAddress.Length > 0)
{
IPAddress ipAddress = IPAddress.Parse(strIPAddress);
IPEndPoint ipep = new IPEndPoint(ipAddress, intPort);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(ipep);
server.Listen(10);
this.toolStripStatusLabelServerMain.Text = "正在监听...";
Socket client = server.Accept();
this.toolStripStatusLabelServerMain.Text = "建立连接成功";
//IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
//string SendFileName = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
//string BagSize = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
//int bagCount = int.Parse(System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client)));
//string bagLast = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
string fileName = "接收的文件(加密)";
string fileaddr = "D:\\" fileName ".txt";
FileStream MyFileStream = new FileStream(fileaddr, FileMode.Create, FileAccess.Write);
//int SendedCount = 0;
while (true)
{
byte[] data = TransferFiles.ReceiveVarData(client);
if (data.Length < 1024)
{
MyFileStream.Write(data, 0, data.Length);
break;
}
else
{
// SendedCount ;
MyFileStream.Write(data, 0, data.Length);
}
}
MyFileStream.Close();
this.toolStripStatusLabelServerMain.Text = "接收完毕";
//给客户端返回信息
string strSendToClient = "OK";
byte[] bytesSendToClient = Encoding.GetEncoding("GB2312").GetBytes(strSendToClient);
client.Send(bytesSendToClient, bytesSendToClient.Length, 0); //向客户端发送信息
//接收客户端发过来的文件MD5值
byte[] bytesReceive = new byte[1024];
int intReceive = client.Receive(bytesReceive, bytesReceive.Length, 0);
strMD5=Encoding.GetEncoding("GB2312").GetString(bytesReceive, 0, intReceive);
client.Close();
MessageBox.Show("文件信息成功接收\n提示:加密文件保存在D:\\接收的文件(加密).txt", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.SetRichTextBoxValue("D:\\接收的文件(加密).txt");
this.toolStripStatusLabelServerMain.Text = "结束监听";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
threadListener.Abort();
return;
}
threadListener.Abort();
}
//private void StartingMonitor()
//{
// try
// {
// int intPort = Convert.ToInt32(this.textBoxPort.Text); //本机开设的端口号
// string strIPAddress = string.Empty; //本机IP地址
// /* 网络连接标志解释
// * 11(在线:拨号上网)
// * 12(在线:通过局域网)
// * 13(在线:代理)
// * 14(MODEM被其他非INTERNET连接占用)
// */
// int connectionState = this.GetConnectedState();
// #region 判断网络连接的类型
// if (11 == connectionState)
// {
// IPAddress[] ipAddresses = this.GetLocalIPAddresses();
// int countIPAddresses = ipAddresses.Length;
// strIPAddress = ipAddresses[countIPAddresses / 2].ToString();
// }
// else if (12 == connectionState)
// {
// IPAddress[] ipAddresses = this.GetLocalIPAddresses();
// int countIPAddresses = ipAddresses.Length;
// strIPAddress = ipAddresses[countIPAddresses / 2].ToString();
// }
// else
// {
// MessageBox.Show("该模块暂时未处理,请联系开发人", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
// return ;
// }
// #endregion
// if (strIPAddress.Length > 0)
// {
// IPAddress ipAddress = IPAddress.Parse(strIPAddress);
// IPEndPoint ipep = new IPEndPoint(ipAddress, intPort);
// mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// mySocket.Bind(ipep); //绑定套接字
// mySocket.Listen(0); //开始监听
// this.SetButtonEnable(true);
// //this.buttonStopMonitor.Enabled = true; //启用停止监听按钮
// this.toolStripStatusLabelServerMain.Text = "正在监听...";
// //接收来自客户端发回的信息
// Socket clientSocket = mySocket.Accept(); //接收客户端的信息
// string strReceive = "";
// byte[] bytesReceive = new byte[1024];
// int lengthBytesReceive = clientSocket.Receive(bytesReceive, bytesReceive.Length, 0); //接收来自客户端的信息
// strReceive = Encoding.GetEncoding("GB2312").GetString(bytesReceive, 0, lengthBytesReceive);
// this.SetRichTextBoxValue(strReceive);
// //this.richTextBoxValue.Text = strReceive;
// this.toolStripStatusLabelServerMain.Text = "已接收客户端信息";
// //给客户端返回信息
// string strSendToClient = "服务器已接收信息";
// byte[] bytesSendToClient = Encoding.GetEncoding("GB2312").GetBytes(strSendToClient);
// clientSocket.Send(bytesReceive, bytesReceive.Length, 0); //向客户端发送信息
// clientSocket.Close();
// mySocket.Close(); //关闭监听
// this.toolStripStatusLabelServerMain.Text = "结束监听";
// }
// }
// catch (Exception ex)
// {
// MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
// return ;
// }
//}
private IPAddress[] GetLocalIPAddresses()
{
IPAddress[] ipAddresses=new IPAddress[]{};
try
{
string strHostName = Dns.GetHostName(); //获取本地计算机主机名
IPHostEntry localhost = Dns.GetHostEntry(strHostName);
ipAddresses = localhost.AddressList;
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return ipAddresses;
}
private void buttonEncrypt_Click(object sender, EventArgs e)
{
try
{
string fileName = "接收的文件(加密)";
string strPath = "D:\\" fileName ".txt";
DES_ des = new DES_("江西财经大学");
string encryptedFilePath = "D:\\" fileName "(加密).txt";
des.Encrypt(strPath, encryptedFilePath);
MessageBox.Show("文件加密成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.richTextBoxValue.LoadFile(encryptedFilePath, RichTextBoxStreamType.PlainText);
this.richTextBoxValue.Update();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void buttonDecrypt_Click(object sender, EventArgs e)
{
try
{
string fileName = "接收的文件(加密)";
string strPath = "D:\\" fileName ".txt";
DES_ des = new DES_("江西财经大学");
des.Decrypt(strPath, "D:\\" fileName "(解密).txt");
MessageBox.Show("文件解密成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.richTextBoxValue.LoadFile("D:\\" fileName "(解密).txt", RichTextBoxStreamType.PlainText);
this.richTextBoxValue.Update();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
///
private void buttonCheckingFile_Click(object sender, EventArgs e)
{
string fileName = "接收的文件(加密)";
string fileaddr = "D:\\" fileName ".txt";
try
{
string strMD5=MD5Help.MD5_.GetFileMD5(fileaddr);
if (this.strMD5 == strMD5)
{
MessageBox.Show("文件验证成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
//this.richTextBoxValue.LoadFile(fileaddr, RichTextBoxStreamType.PlainText);
//this.richTextBoxValue.Update();
return;
}
else
{
MessageBox.Show("文件验证失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.richTextBoxValue.Clear();
return;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
}
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论