我正在尝试通过TCP连接交换公钥。如果我可以将这些密钥存储在数据包类中,对数据包对象进行序列化,将其转换为字节数组然后通过tcp连接进行发送,则对我来说更容易。
我遇到的问题是,通过此方法返回加密消息时,解密失败的时间最多。我不确定为什么会这样,但是根据我对Encoding.Unicode库的了解,如果您要发送密钥,可能会导致损坏。我正在寻找的是一种通过tcp连接发送这些密钥(最好是JSON格式)而不损坏它们的方法。
我还读到Convert.FromBase64String()是无损坏编码的来源,但由于格式不正确,它似乎不能总是能够转换JSON字符串。
//Sets up a tcp conncetion and encrypts a packet
void EncryptAndSend()
{
//Recieve a string with the public key of the other side with this packet method except I don't encrypt that packet
//The key is in the format given by rsa.ToXmlString
string pub_key = "public_key_xml_format";
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(pub_key);
string plaintext = "Some plaintext";
string password = "pass";
Packet packet = new Packet(PacketType.ENCRYPTED_MESSAGE, plaintext, 0, 1);
string encrypted_plain = SymmetricEncrypt(plaintext, password);
packet.payload = encrypted_plain;
packet.password = Encoding.Unicode.GetString(rsa.Encrypt(Encoding.Unicode.GetBytes(password), false));
string serialized_packet = new JavaScriptSerializer().Serialize(packet);
byte[] bytes = Encoding.Unicode.GetBytes(serialized_packet);
var client = new TcpClient("127.0.0.1", 5300);
client.GetStream().Write(bytes, 0, bytes.Length);
}
//Sets up a tcp connection and decrypts a packet
void RecieveAndDecrypt()
{
var listener = new TcpListener(IPAddress.Loopback, 5300);
listener.Start();
TcpClient client = listener.AcceptTcpClient();
var stream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
while (client.Connected)
{
try
{
Array.Clear(buffer, 0, buffer.Length);
int bytesRead = stream.Read(buffer, 0, client.ReceiveBufferSize);
Decrypt(buffer);
}
catch
{
Console.WriteLine("Client disconnected");
}
}
}
//Decrypts and prints the packet payload
void Decrypt(byte[] buffer)
{
string pub_key = "lol";
string strbuf = Encoding.Unicode.GetString(buffer);
Packet packet = new JavaScriptSerializer().Deserialize<Packet>(strbuf);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(pub_key);
byte[] decrypt_pass = rsa.Decrypt(Encoding.Unicode.GetBytes(packet.password), false);
string decrypted_payload = SymmetricDecrypt(packet.payload, Encoding.Unicode.GetString(decrypt_pass));
Console.WriteLine(decrypted_payload);
}
我在一个线程中运行加密器,在另一个线程中运行解密器。在运行它们之前,我以xml字符串的形式从解密端发送公钥。我省去了这段代码,因为我认为我的模型已经足够长了,而且我不想让任何人不知所措。如果您想要原始的项目源代码,那么我会很乐意将其转储。
我忘了补充:在解密和加密数据包之前,我已经完成了控制台打印,以查看用于加密和解密特定数据包的公钥和私钥。据我所知,这些印刷品是相同的,但是由于编码的原因,有些地方可能会有所不同,但我看不到。
我尝试解密时抛出的异常是:参数不正确。