温馨提示×

C# TcpIp如何进行数据加密

c#
小樊
83
2024-07-22 21:49:14
栏目: 编程语言

在C#中进行TcpIp数据加密可以通过使用加密算法来对数据进行加密和解密。以下是一个简单的示例代码:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Security.Cryptography;

public class TcpIpEncryption
{
    private static byte[] key = Encoding.UTF8.GetBytes("0123456789abcdef");
    private static byte[] iv = Encoding.UTF8.GetBytes("abcdef9876543210");

    public static void Main()
    {
        TcpListener server = null;
        try
        {
            Int32 port = 13000;
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");

            server = new TcpListener(localAddr, port);
            server.Start();

            Byte[] bytes = new Byte[256];
            String data = null;

            while (true)
            {
                Console.WriteLine("Waiting for a connection...");

                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("Connected!");

                data = null;

                NetworkStream stream = client.GetStream();

                int i;
                while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    data = Encoding.UTF8.GetString(bytes, 0, i);
                    Console.WriteLine("Received: {0}", data);

                    // Decrypt received data
                    string decryptedData = DecryptStringFromBytes_Aes(Convert.FromBase64String(data), key, iv);
                    Console.WriteLine("Decrypted: {0}", decryptedData);

                    // Encrypt response data
                    string response = "Response from server";
                    byte[] encryptedResponse = EncryptStringToBytes_Aes(response, key, iv);

                    // Send the encrypted response back to client
                    stream.Write(encryptedResponse, 0, encryptedResponse.Length);
                    Console.WriteLine("Sent: {0}", response);
                }

                client.Close();
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }
        finally
        {
            server.Stop();
        }

        Console.WriteLine("\nHit enter to continue...");
        Console.Read();
    }

    static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
    {
        byte[] encrypted;

        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;

            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }

        return encrypted;
    }

    static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
    {
        string plaintext = null;

        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;

            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
        }

        return plaintext;
    }
}

在示例代码中,使用AES对称加密算法对传输的数据进行加密和解密。在EncryptStringToBytes_Aes方法中,将明文进行AES加密并返回加密后的字节数组。在DecryptStringFromBytes_Aes方法中,将密文进行AES解密并返回解密后的字符串。在接收数据后,先进行解密操作,然后对响应数据进行加密后发送给客户端。

0