C#实现数据包加密与解密实例详解
在很多项目中,为了安全安全考虑,需要对数据包进行加密处理,本文实例所述的即为C#加密代码,在应用开发中有很大的实用价值。说起数据包加密,其实对C#编程者来说,应该是一个基础的技巧,是进行C#程序设计人员必须要掌握的技能。
C#实现加密功能的核心代码如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Threading;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Net.NetworkInformation;
usingSystem.Security.Cryptography;
usingSystem.IO;
namespaceEncryptDataReport
{
publicpartialclassForm1:Form
{
publicForm1()
{
InitializeComponent();
}
#region定义全局对象及变量
privateIPEndPointServer;//服务器端
privateIPEndPointClient;//客户端
privateSocketmySocket;//套接字
privateEndPointClientIP;//IP地址
byte[]buffer,data;//接收缓存
boolblFlag=true;//标识是否第一次发送信息
boolISPort=false;//判断端口打开
intSendNum1,ReceiveNum1,DisNum1;//记录窗体加载时的已发送\已接收\丢失的数据报
intSendNum2,ReceiveNum2,DisNum2;//记录当前已发送\已接收\丢失的数据报
intSendNum3,ReceiveNum3,DisNum3;//缓存已发送\已接收\丢失的数据报
intport;//端口号
#endregion
//异步接收信息
privatevoidStartLister(IAsyncResultIAResult)
{
intNum=mySocket.EndReceiveFrom(IAResult,refClientIP);
stringstrInfo=Encoding.Unicode.GetString(buffer,0,Num);
rtbContent.AppendText("用户"+ClientIP.ToString());
rtbContent.AppendText(":");
rtbContent.AppendText("\r\n");
rtbContent.AppendText(DecryptDES(strInfo,"mrsoftxk"));//对接收到的信息进行解密
rtbContent.AppendText("\r\n");
mySocket.BeginReceiveFrom(buffer,0,buffer.Length,SocketFlags.None,refClientIP,newAsyncCallback(StartLister),null);
}
//初始化已发送、已接收和丢失的数据报
privatevoidForm1_Load(objectsender,EventArgse)
{
if(blFlag==true)
{
IPGlobalPropertiesNetInfo=IPGlobalProperties.GetIPGlobalProperties();
UdpStatisticsmyUdpStat=null;
myUdpStat=NetInfo.GetUdpIPv4Statistics();
SendNum1=Int32.Parse(myUdpStat.DatagramsSent.ToString());
ReceiveNum1=Int32.Parse(myUdpStat.DatagramsReceived.ToString());
DisNum1=Int32.Parse(myUdpStat.IncomingDatagramsDiscarded.ToString());
}
}
//设置端口号
privatevoidbutton4_Click(objectsender,EventArgse)
{
try
{
port=Convert.ToInt32(textBox4.Text);
CheckForIllegalCrossThreadCalls=false;
buffer=newbyte[1024];
data=newbyte[1024];
Server=newIPEndPoint(IPAddress.Any,port);
Client=newIPEndPoint(IPAddress.Broadcast,port);
ClientIP=(EndPoint)Server;
mySocket=newSocket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
mySocket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.Broadcast,1);
mySocket.Bind(Server);
mySocket.BeginReceiveFrom(buffer,0,buffer.Length,SocketFlags.None,refClientIP,newAsyncCallback(StartLister),null);
ISPort=true;//打开指定端口号
}
catch{}
}
//发送信息
privatevoidbutton2_Click(objectsender,EventArgse)
{
if(ISPort==true)//判断是否有打开的端口号
{
IPGlobalPropertiesNetInfo=IPGlobalProperties.GetIPGlobalProperties();
UdpStatisticsmyUdpStat=null;
myUdpStat=NetInfo.GetUdpIPv4Statistics();
try
{
if(blFlag==false)//非第一次发送
{
SendNum2=Int32.Parse(myUdpStat.DatagramsSent.ToString());
ReceiveNum2=Int32.Parse(myUdpStat.DatagramsReceived.ToString());
DisNum2=Int32.Parse(myUdpStat.IncomingDatagramsDiscarded.ToString());
textBox1.Text=Convert.ToString(SendNum2-SendNum3);
textBox2.Text=Convert.ToString(ReceiveNum2-ReceiveNum3);
textBox3.Text=Convert.ToString(DisNum2-DisNum3);
}
SendNum2=Int32.Parse(myUdpStat.DatagramsSent.ToString());
ReceiveNum2=Int32.Parse(myUdpStat.DatagramsReceived.ToString());
DisNum2=Int32.Parse(myUdpStat.IncomingDatagramsDiscarded.ToString());
SendNum3=SendNum2;//记录本次的发送数据报
ReceiveNum3=ReceiveNum2;//记录本次的接收数据报
DisNum3=DisNum2;//记录本次的丢失数据报
if(blFlag==true)//第一次发送
{
textBox1.Text=Convert.ToString(SendNum2-SendNum1);
textBox2.Text=Convert.ToString(ReceiveNum2-ReceiveNum1);
textBox3.Text=Convert.ToString(DisNum2-DisNum1);
blFlag=false;
}
}
catch(Exceptionex)
{
MessageBox.Show(ex.Message,"提示信息",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
stringstr=EncryptDES(rtbSend.Text,"mrsoftxk");//加密要发送的信息
data=Encoding.Unicode.GetBytes(str);
mySocket.SendTo(data,data.Length,SocketFlags.None,Client);
rtbSend.Text="";
}
else
{
MessageBox.Show("请首先打开端口!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
button4.Focus();
}
}
//清屏
privatevoidbutton1_Click(objectsender,EventArgse)
{
rtbContent.Clear();
}
//退出
privatevoidbutton3_Click(objectsender,EventArgse)
{
Application.Exit();
}
//按<Ctrl+Enter>组合键发送信息
privatevoidrtbSend_KeyDown(objectsender,KeyEventArgse)
{
//当同时按下Ctrl和Enter时,发送消息
if(e.Control&&e.KeyValue==13)
{
e.Handled=true;
button2_Click(this,null);
}
}
//聊天记录随时滚动
privatevoidrtbContent_TextChanged(objectsender,EventArgse)
{
rtbContent.ScrollToCaret();
}
privatestaticbyte[]Keys={0x12,0x34,0x56,0x78,0x90,0xAB,0xCD,0xEF};//密钥
#regionDES加密字符串
///<summary>
///DES加密字符串
///</summary>
///<paramname="str">待加密的字符串</param>
///<paramname="key">加密密钥,要求为8位</param>
///<returns>加密成功返回加密后的字符串,失败返回源字符串</returns>
publicstringEncryptDES(stringstr,stringkey)
{
try
{
byte[]rgbKey=Encoding.UTF8.GetBytes(key.Substring(0,8));
byte[]rgbIV=Keys;
byte[]inputByteArray=Encoding.UTF8.GetBytes(str);
DESCryptoServiceProvidermyDES=newDESCryptoServiceProvider();
MemoryStreamMStream=newMemoryStream();
CryptoStreamCStream=newCryptoStream(MStream,myDES.CreateEncryptor(rgbKey,rgbIV),CryptoStreamMode.Write);
CStream.Write(inputByteArray,0,inputByteArray.Length);
CStream.FlushFinalBlock();
returnConvert.ToBase64String(MStream.ToArray());
}
catch
{
returnstr;
}
}
#endregion
#regionDES解密字符串
///<summary>
///DES解密字符串
///</summary>
///<paramname="str">待解密的字符串</param>
///<paramname="key">解密密钥,要求为8位,和加密密钥相同</param>
///<returns>解密成功返回解密后的字符串,失败返源字符串</returns>
publicstringDecryptDES(stringstr,stringkey)
{
try
{
byte[]rgbKey=Encoding.UTF8.GetBytes(key);
byte[]rgbIV=Keys;
byte[]inputByteArray=Convert.FromBase64String(str);
DESCryptoServiceProvidermyDES=newDESCryptoServiceProvider();
MemoryStreamMStream=newMemoryStream();
CryptoStreamCStream=newCryptoStream(MStream,myDES.CreateDecryptor(rgbKey,rgbIV),CryptoStreamMode.Write);
CStream.Write(inputByteArray,0,inputByteArray.Length);
CStream.FlushFinalBlock();
returnEncoding.UTF8.GetString(MStream.ToArray());
}
catch
{
returnstr;
}
}
#endregion
}
}
本例备有详细的注释,对于开发者而言应该不难理解,读者可以根据自身项目需要改进本例代码以符合自身应用需求。