91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

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
成武县| 宜城市| 招远市| 延长县| 什邡市| 科技| 伊川县| 自贡市| 西盟| 方山县| 本溪市| 广饶县| 平南县| 封丘县| 绥阳县| 扶绥县| 莲花县| 山东省| 辉南县| 四子王旗| 西和县| 盐池县| 隆回县| 萝北县| 威信县| 葫芦岛市| 米泉市| 南澳县| 久治县| 吴川市| 巩留县| 乐平市| 姚安县| 成安县| 青州市| 大冶市| 兰州市| 南靖县| 武陟县| 涪陵区| 阳朔县|