通过LAN发送文件

时间:2017-12-19 23:22:40

标签: c# encryption public-key-encryption

使用Tcp通过LAN发送和接收文件的简单程序

  

我希望使用对称和非对称密钥方法加密文件并通过LAN发送,首先是AES加密/解密,然后使用RSA加密/解密对称密钥

场景示例

  

johan希望安全地向Alice发送文件johan必须使用他的用户名和密码登录到应用程序(如果已注册)。   如果.not,johan必须创建用户名和密码如果是第一次注册,    johan必须生成一对密钥(公钥和.Private密钥)。    发布公钥并保密私钥将文件发送给Alice,    johan从应用程序生成随机密钥,以使用AES在文件的加密过程中使用。    文件加密完成后,    johan使用Alice发布的公钥使用RSA加密密钥并发送文件。    使用加密密钥当Alice收到文件时,    她必须登录应用程序并使用她存储的私钥来解密RSA加密密钥。    之后,她使用解密密钥解密文件

这是我的代码

  

但是我很难理解c#中的加密库我不知道从哪里开始请任何人帮助我

GUI

Groupbox called "Send" contain 2 textbox and 2 buttons
 1 - type : textbox name : SrcFilePathTextBox    for   Path
 2 - type : textbox name : DstAddressTextBox     for  Target IP
 3 - type : Button  name : SrcFilePathBrowseButton     for  open file dialog 
 4 - type : Button  name : SendButton        for  start sending Process

 groupbox called "receive" contain textbox and 2 buttons
 1 - type : textbox name : LocalhostInfoTextBox    for   Show PC LAN INFO
 2 - type : Button  name : LocalhostInfoLoadButton     for  Put Info In      textbox
 3 - type : Button  name : ReceiveWaitButton   for  start receiving Process
 and at the end progress bar

守则

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Diagnostics;
namespace JustSendItPrototype
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void SrcFilePathBrowseButton_Click(object sender, EventArgs e)
    {
        if (SrcOpenFileDialog.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            SrcFilePathTextBox.Text = SrcOpenFileDialog.FileName;
    }
    const int PORT = 32665;
    const int BUF_SIZE = 65536;
    private void ReceiveWaitButton_Click(object sender, EventArgs e)
    {
        try
        {
            TcpListener tcpListener = new TcpListener(IPAddress.Any, 32665);
            tcpListener.Start();
            using (TcpClient tcpClient = tcpListener.AcceptTcpClient())
            {
                using (NetworkStream networkStream = tcpClient.GetStream())
                {
                    using (BinaryReader reader = new BinaryReader(networkStream))
                    {
                        using (BinaryWriter writer = new BinaryWriter(networkStream))
                        {
                            string fileName = reader.ReadString();
                            long fileLength = reader.ReadInt64();
                            Debug.Print("FileName={0}, FileLength={1}", fileName, fileLength);
                            DstSaveFileDialog.FileName = fileName;
                            if (DstSaveFileDialog.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                            {
                                using (FileStream fileStream = new FileStream(DstSaveFileDialog.FileName, FileMode.Create))
                                {
                                    if (fileLength > 0)
                                    {
                                        byte[] buf = new byte[BUF_SIZE];
                                        long bytesLeft = fileLength;
                                        while (bytesLeft > 0)
                                        {
                                            int bytesToTransfer = (int)Math.Min(bytesLeft, (long)BUF_SIZE);
                                            Debug.Print("Reading {0} B", bytesToTransfer);
                                            int bytesRead = reader.Read(buf, 0, bytesToTransfer);
                                            Debug.Print("Read {0} B", bytesRead);
                                            if (bytesRead > 0)
                                            {
                                                fileStream.Write(buf, 0, bytesRead);
                                                bytesLeft -= bytesRead;
                                                ProgressBar1.Value = 1000 - (int)(bytesLeft * 1000 / fileLength);
                                            }
                                            else
                                                System.Threading.Thread.Sleep(30);
                                        }
                                    }
                                    Debug.Print("Sending confirmation");
                                    writer.Write((byte)1);
                                    MessageBox.Show(this, "File received successfully.", "Receive File", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(this, ex.Message, "Receive File", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
    private void SendButton_Click(object sender, EventArgs e)
    {
        try
        {
            string srcFilePath = SrcFilePathTextBox.Text;
            FileInfo fileInfo = new FileInfo(srcFilePath);
            long fileLength = fileInfo.Length;

            using (FileStream fileStream = new FileStream(srcFilePath, FileMode.Open))
            {
                using (TcpClient sendingClient = new TcpClient(DstAddressTextBox.Text, PORT))
                {
                    using (NetworkStream sendingStream = sendingClient.GetStream())
                    {
                        using (BinaryWriter binaryWriter = new BinaryWriter(sendingStream))
                        {
                            using (BinaryReader binaryReader = new BinaryReader(sendingStream))
                            {
                                string fileName = Path.GetFileName(srcFilePath);
                                binaryWriter.Write(fileName);
                                binaryWriter.Write(fileLength);
                                Debug.Print("FileName={0}, FileLength={1}", fileName, fileLength);

                                if (fileLength > 0)
                                {
                                    byte[] buf = new byte[BUF_SIZE];
                                    long bytesLeft = fileLength;
                                    while (bytesLeft > 0)
                                    {
                                        int bytesToTransfer = (int)Math.Min(bytesLeft, (long)BUF_SIZE);
                                        fileStream.Read(buf, 0, bytesToTransfer);
                                        Debug.Print("Sending {0} B", bytesToTransfer);
                                        binaryWriter.Write(buf, 0, bytesToTransfer);
                                        bytesLeft -= bytesToTransfer;
                                        ProgressBar1.Value = 1000 - (int)(bytesLeft * 1000 / fileLength);
                                    }
                                }

                                Debug.Print("Reading confirmation...");
                                byte answer = binaryReader.ReadByte();
                                if (answer == 1)
                                    MessageBox.Show(this, "File sent successfully.", "Send File", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(this, ex.Message, "Send File", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
    private void LocalhostInfoLoadButton_Click(object sender, EventArgs e)
    {
        try
        {
            System.Text.StringBuilder sb = new StringBuilder();

            string hostname = Dns.GetHostName();
            sb.Append("Hostname: ");
            sb.Append(hostname);
            sb.Append("\r\n");

            IPAddress[] addresses = Dns.GetHostAddresses(hostname);
            foreach (IPAddress address in addresses)
            {
                sb.Append("IP: ");
                sb.Append(address.ToString());
                sb.Append("\r\n");
            }

            LocalhostInfoTextBox.Text = sb.ToString();
        }
        catch (Exception ex)
        {
            MessageBox.Show(this, ex.Message, "Send File", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}
}

1 个答案:

答案 0 :(得分:0)

我现在不在电脑上,但完成场景的最简单方法是在两端使用SslStream。

在服务器(Johan)上有传入连接后,从TcpStream创建一个SslStream。在服务器上,您将使用SslStream.AuthenticateAsServer(),此方法接受X509Certificate(这将是您的私钥)。

在客户端(Alice)上,您将改为使用SslStream.AuthenticateAsClient。

对于这两种方法,您都可以传递证书验证回调。在您的情况下,您只能在客户端执行此操作,并检查给定的证书是由Johan提供的证书。

编辑:我已经重新阅读了您的问题,并且按照您的要求,我创建了一个example,它首先发送一个使用RSA加密的密钥并使用该密钥加密以下数据

收到某些数据后,首先解密密钥,然后用于AES解密。这是一个非常粗略的例子,我没有注册和登录,我有证书存储,所以他们都有私钥和公钥,但应该足以让你实现目标

相关问题