亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

c# tcpclient 的數據加密和解密怎樣實現

c#
小樊
86
2024-08-15 00:52:46
欄目: 編程語言

在C#中,可以使用加密算法來對TCPClient傳輸的數據進行加密和解密。以下是一個簡單的示例來實現數據加密和解密:

  1. 導入必要的命名空間:
using System;
using System.Text;
using System.Security.Cryptography;
  1. 創建一個加密類,包含加密和解密方法:
public class EncryptionHelper
{
    private static readonly string Key = "YourKey1234567890"; // 16位密鑰
    private static readonly string IV = "YourIV1234567890"; // 16位初始化向量

    public static string Encrypt(string plainText)
    {
        byte[] keyBytes = Encoding.UTF8.GetBytes(Key);
        byte[] ivBytes = Encoding.UTF8.GetBytes(IV);

        using (Aes aes = Aes.Create())
        {
            aes.Key = keyBytes;
            aes.IV = ivBytes;

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

            byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
            byte[] encryptedBytes = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);

            return Convert.ToBase64String(encryptedBytes);
        }
    }

    public static string Decrypt(string encryptedText)
    {
        byte[] keyBytes = Encoding.UTF8.GetBytes(Key);
        byte[] ivBytes = Encoding.UTF8.GetBytes(IV);

        using (Aes aes = Aes.Create())
        {
            aes.Key = keyBytes;
            aes.IV = ivBytes;

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

            byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
            byte[] decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);

            return Encoding.UTF8.GetString(decryptedBytes);
        }
    }
}
  1. 在TCPClient中使用加密類進行數據加密和解密:
// 創建TCPClient
TcpClient client = new TcpClient("127.0.0.1", 8888);
NetworkStream stream = client.GetStream();

// 發送加密數據
string plainText = "Hello, world!";
string encryptedText = EncryptionHelper.Encrypt(plainText);
byte[] data = Encoding.UTF8.GetBytes(encryptedText);
stream.Write(data, 0, data.Length);

// 接收加密數據
byte[] receiveBuffer = new byte[1024];
int bytesRead = stream.Read(receiveBuffer, 0, receiveBuffer.Length);
string receivedData = Encoding.UTF8.GetString(receiveBuffer, 0, bytesRead);
string decryptedText = EncryptionHelper.Decrypt(receivedData);
Console.WriteLine(decryptedText);

// 關閉連接
client.Close();

在上面的示例中,我們創建了一個加密類EncryptionHelper來實現數據的加密和解密功能。在TCPClient中發送加密數據和接收加密數據時,分別調用了EncryptionHelper中的Encrypt和Decrypt方法來進行加密和解密操作。最后關閉連接時,記得關閉TcpClient。

0
庆阳市| 仪陇县| 临沭县| 宿州市| 东至县| 启东市| 孟连| 江孜县| 鄢陵县| 扎鲁特旗| 克拉玛依市| 肃北| 汉阴县| 石狮市| 龙胜| 尉氏县| 宜川县| 济南市| 个旧市| 义乌市| 龙南县| 龙州县| 安宁市| 万全县| 漳平市| 凤山县| 怀仁县| 苏尼特左旗| 红安县| 广昌县| 峡江县| 扎赉特旗| 通化县| 化德县| 青河县| 云林县| 堆龙德庆县| 克拉玛依市| 昭觉县| 淮南市| 澳门|