在C#中,可以使用加密算法來對TCPClient傳輸的數據進行加密和解密。以下是一個簡單的示例來實現數據加密和解密:
using System;
using System.Text;
using System.Security.Cryptography;
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);
}
}
}
// 創建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。