Login Protocol: Encryption - Afr0Games/Project-Dollhouse GitHub Wiki
Description: Encryption happens using .NET's CryptoStream class, using the ASCII string "@1B2c3D4e5F6g7H8" as an initialization vector. Read about CryptoStream here: http://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptostream(v=vs.71).aspx
Code:
/// <summary>
/// Writes a packet's header and encrypts the contents of the packet (not the header).
/// </summary>
/// <param name="PacketID">The ID of the packet.</param>
/// <param name="PacketData">The packet's contents.</param>
/// <returns>The finalized packet!</returns>
/// <summary>
/// Writes a packet's header and encrypts the contents of the packet (not the header).
/// </summary>
/// <param name="PacketID">The ID of the packet.</param>
/// <param name="PacketData">The packet's contents.</param>
/// <returns>The finalized packet!</returns>
private byte[] FinalizePacket(byte PacketID, byte[] PacketData)
{
MemoryStream FinalizedPacket = new MemoryStream();
BinaryWriter PacketWriter = new BinaryWriter(FinalizedPacket);
MemoryStream TempStream = new MemoryStream();
CryptoStream EncryptedStream = new CryptoStream(TempStream,
CryptoService.CreateEncryptor(EncKey, Encoding.ASCII.GetBytes("@1B2c3D4e5F6g7H8")),
CryptoStreamMode.Write);
EncryptedStream.Write(PacketData, 0, PacketData.Length);
EncryptedStream.FlushFinalBlock();
PacketWriter.Write(PacketID);
//The length of the encrypted data can be longer or smaller than the original length,
//so write the length of the encrypted data.
PacketWriter.Write((ushort)(5 + TempStream.Length));
//Also write the length of the unencrypted data.
PacketWriter.Write((ushort)PacketData.Length);
PacketWriter.Flush();
PacketWriter.Write(TempStream.ToArray());
PacketWriter.Flush();
byte[] ReturnPacket = FinalizedPacket.ToArray();
PacketWriter.Close();
return ReturnPacket;
}