在C#中進行TcpIp數(shù)據(jù)加密可以通過使用加密算法來對數(shù)據(jù)進行加密和解密。以下是一個簡單的示例代碼:
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對稱加密算法對傳輸?shù)臄?shù)據(jù)進行加密和解密。在EncryptStringToBytes_Aes
方法中,將明文進行AES加密并返回加密后的字節(jié)數(shù)組。在DecryptStringFromBytes_Aes
方法中,將密文進行AES解密并返回解密后的字符串。在接收數(shù)據(jù)后,先進行解密操作,然后對響應數(shù)據(jù)進行加密后發(fā)送給客戶端。