在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。