基本信息
源码名称:C# pki编程 实例源码(含服务端和客户端)
源码大小:0.29M
文件格式:.rar
开发语言:C#
更新时间:2017-12-29
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
pki信息加密
pki信息加密
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)
{
}
}
}