C#实现数据包加密与解密实例详解
作者:shichen2014 发布时间:2022-05-14 18:44:50
标签:C#,数据包,加密,解密
在很多项目中,为了安全安全考虑,需要对数据包进行加密处理,本文实例所述的即为C#加密代码,在应用开发中有很大的实用价值。说起数据包加密,其实对C#编程者来说,应该是一个基础的技巧,是进行C#程序设计人员必须要掌握的技能。
C#实现加密功能的核心代码如下:
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.Threading;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.IO;
namespace EncryptDataReport
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
#region 定义全局对象及变量
private IPEndPoint Server;//服务器端
private IPEndPoint Client;//客户端
private Socket mySocket;//套接字
private EndPoint ClientIP;//IP地址
byte[] buffer, data;//接收缓存
bool blFlag = true;//标识是否第一次发送信息
bool ISPort = false;//判断端口打开
int SendNum1, ReceiveNum1, DisNum1; //记录窗体加载时的已发送\已接收\丢失的数据报
int SendNum2, ReceiveNum2, DisNum2; //记录当前已发送\已接收\丢失的数据报
int SendNum3, ReceiveNum3, DisNum3; //缓存已发送\已接收\丢失的数据报
int port;//端口号
#endregion
//异步接收信息
private void StartLister(IAsyncResult IAResult)
{
int Num = mySocket.EndReceiveFrom(IAResult, ref ClientIP);
string strInfo = 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, ref ClientIP, new AsyncCallback(StartLister), null);
}
//初始化已发送、已接收和丢失的数据报
private void Form1_Load(object sender, EventArgs e)
{
if (blFlag == true)
{
IPGlobalProperties NetInfo = IPGlobalProperties.GetIPGlobalProperties();
UdpStatistics myUdpStat = null;
myUdpStat = NetInfo.GetUdpIPv4Statistics();
SendNum1 = Int32.Parse(myUdpStat.DatagramsSent.ToString());
ReceiveNum1 = Int32.Parse(myUdpStat.DatagramsReceived.ToString());
DisNum1 = Int32.Parse(myUdpStat.IncomingDatagramsDiscarded.ToString());
}
}
//设置端口号
private void button4_Click(object sender, EventArgs e)
{
try
{
port = Convert.ToInt32(textBox4.Text);
CheckForIllegalCrossThreadCalls = false;
buffer = new byte[1024];
data = new byte[1024];
Server = new IPEndPoint(IPAddress.Any, port);
Client = new IPEndPoint(IPAddress.Broadcast, port);
ClientIP = (EndPoint)Server;
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
mySocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
mySocket.Bind(Server);
mySocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref ClientIP, new AsyncCallback(StartLister), null);
ISPort = true;//打开指定端口号
}
catch { }
}
//发送信息
private void button2_Click(object sender, EventArgs e)
{
if (ISPort == true)//判断是否有打开的端口号
{
IPGlobalProperties NetInfo = IPGlobalProperties.GetIPGlobalProperties();
UdpStatistics myUdpStat = 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 (Exception ex)
{
MessageBox.Show(ex.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
string str = 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();
}
}
//清屏
private void button1_Click(object sender, EventArgs e)
{
rtbContent.Clear();
}
//退出
private void button3_Click(object sender, EventArgs e)
{
Application.Exit();
}
//按<Ctrl+Enter>组合键发送信息
private void rtbSend_KeyDown(object sender, KeyEventArgs e)
{
//当同时按下Ctrl和Enter时,发送消息
if (e.Control && e.KeyValue == 13)
{
e.Handled = true;
button2_Click(this, null);
}
}
//聊天记录随时滚动
private void rtbContent_TextChanged(object sender, EventArgs e)
{
rtbContent.ScrollToCaret();
}
private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };//密钥
#region DES加密字符串
///<summary>
///DES加密字符串
///</summary>
///<param name="str">待加密的字符串</param>
///<param name="key">加密密钥,要求为8位</param>
///<returns>加密成功返回加密后的字符串,失败返回源字符串</returns>
public string EncryptDES(string str, string key)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(key.Substring(0, 8));
byte[] rgbIV = Keys;
byte[] inputByteArray = Encoding.UTF8.GetBytes(str);
DESCryptoServiceProvider myDES = new DESCryptoServiceProvider();
MemoryStream MStream = new MemoryStream();
CryptoStream CStream = new CryptoStream(MStream, myDES.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
CStream.Write(inputByteArray, 0, inputByteArray.Length);
CStream.FlushFinalBlock();
return Convert.ToBase64String(MStream.ToArray());
}
catch
{
return str;
}
}
#endregion
#region DES解密字符串
///<summary>
///DES解密字符串
///</summary>
///<param name="str">待解密的字符串</param>
///<param name="key">解密密钥,要求为8位,和加密密钥相同</param>
///<returns>解密成功返回解密后的字符串,失败返源字符串</returns>
public string DecryptDES(string str, string key)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(key);
byte[] rgbIV = Keys;
byte[] inputByteArray = Convert.FromBase64String(str);
DESCryptoServiceProvider myDES = new DESCryptoServiceProvider();
MemoryStream MStream = new MemoryStream();
CryptoStream CStream = new CryptoStream(MStream, myDES.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
CStream.Write(inputByteArray, 0, inputByteArray.Length);
CStream.FlushFinalBlock();
return Encoding.UTF8.GetString(MStream.ToArray());
}
catch
{
return str;
}
}
#endregion
}
}
本例备有详细的注释,对于开发者而言应该不难理解,读者可以根据自身项目需要改进本例代码以符合自身应用需求。
0
投稿
猜你喜欢
- Spring Framework 提供了一套可以方便地对 Controller 层中接收的参数进行校验的框架,其中就包括了 @Validat
- 注解作用注解是JDK1.5版本开始引入的一个特性,用于对代码进行说明,可以对包、类、接口、字段、方法参数、局部变量等进行注解。它主要的作用有
- 一. 引入相关jar包首先,我们先在idea里创建出一个Maven项目出来,除了路径要填成自己的希望路径以外,其他都可以一路next和fin
- 一、首先在Spring Boot项目中,手动添加异常方法进行测试@Transactional(rollbackFor=Exception.c
- 前言:最近在工程中需要用到截取RotatedRect中的图形,保存为Mat做后续处理。发现opencv文档中没有这个api,最开始想到的方案
- Map简介将键映射到值的对象。一个映射不能包含重复的键;每个键最多只能映射到一个值。此接口取代 Dictionary 类,后者完全是一个抽象
- 文件上传和下载是web开发中常遇到的问题,这几天在做一个项目又用到了文件下载,之前也零零散散记了些笔记,今天来做一下整理。文件上传还有待进一
- 本文实例为大家分享了java实现猜拳小游戏的具体代码,供大家参考,具体内容如下实现下图要求public class User {privat
- 概要本节要实现的是多表关联查询的简单demo。场景是根据id查询某商品分类信息,并展示该分类下的商品列表。一、Mysql测试数据新建表Cat
- 导出Excel的框架有很多种,POI相对来说比较老了,很多Excel框架底层都是POI、有EasyPoi、EasyExcel、包括Hutoo
- 页面代码:<%@ page language="java" contentType="text/html
- Memento定义:memento是一个保存另外一个对象内部状态拷贝的对象,这样以后就可以将该对象恢复到原先保存的状态。Memento模式相
- 一.对象在JVM的内存结构JAVA内存管理由JVM来管理。1)堆,所有new出来的对象(包括成员变量)2)栈,所有局部变量(包括方法的参数)
- 一个框架的使用,必然离不开其中的组件支持。我们在下载完mybatis框架后,因为大部分的内部结构还没有启动,就要手动的对其进行配置。在之前有
- 这篇文章主要介绍了springboot自定义异常视图过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需
- 在开发中,我们通常需要将从数据库中查询的集合数据转换成类似文件系统一样的树形集合,比如:省市单位,部门机构,书籍分类等TreeNode对象@
- BeanFactory接口:IoC容器的顶级接口,是IoC容器的最基础实现,也是访问Spring容器的根接口,负责对bean的创建,访问等工
- 本文实例为大家分享了Java实现简易俄罗斯方块的具体代码,供大家参考,具体内容如下一、将对象抽象为类首先考虑俄罗斯方块游戏中含有哪些具体的对
- 我们都知道mybatis在进行参数判断的时候,直接可以用<if test=""></if> 就可
- IDEA创建一个传统JAVA WEB项目(不使用maven构建)方法一File --> NEW --> Project --&g