internal static BitStream WrapMessage(byte messageType, uint clientId, BitStream messageBody, SecuritySendFlags flags) { try { bool encrypted = ((flags & SecuritySendFlags.Encrypted) == SecuritySendFlags.Encrypted) && NetworkingManager.Singleton.NetworkConfig.EnableEncryption; bool authenticated = (flags & SecuritySendFlags.Authenticated) == SecuritySendFlags.Authenticated && NetworkingManager.Singleton.NetworkConfig.EnableEncryption; PooledBitStream outStream = PooledBitStream.Get(); using (PooledBitWriter outWriter = PooledBitWriter.Get(outStream)) { outWriter.WriteBit(encrypted); outWriter.WriteBit(authenticated); #if !DISABLE_CRYPTOGRAPHY if (authenticated || encrypted) { outWriter.WritePadBits(); long hmacWritePos = outStream.Position; if (authenticated) { outStream.Write(HMAC_PLACEHOLDER, 0, HMAC_PLACEHOLDER.Length); } if (encrypted) { using (RijndaelManaged rijndael = new RijndaelManaged()) { rijndael.GenerateIV(); rijndael.Padding = PaddingMode.PKCS7; byte[] key = NetworkingManager.Singleton.IsServer ? CryptographyHelper.GetClientKey(clientId) : CryptographyHelper.GetServerKey(); if (key == null) { if (LogHelper.CurrentLogLevel <= LogLevel.Error) { LogHelper.LogError("Failed to grab key"); } return(null); } rijndael.Key = key; outStream.Write(rijndael.IV); using (CryptoStream encryptionStream = new CryptoStream(outStream, rijndael.CreateEncryptor(), CryptoStreamMode.Write)) { encryptionStream.WriteByte(messageType); encryptionStream.Write(messageBody.GetBuffer(), 0, (int)messageBody.Length); } } } else { outStream.WriteByte(messageType); outStream.Write(messageBody.GetBuffer(), 0, (int)messageBody.Length); } if (authenticated) { byte[] key = NetworkingManager.Singleton.IsServer ? CryptographyHelper.GetClientKey(clientId) : CryptographyHelper.GetServerKey(); if (key == null) { if (LogHelper.CurrentLogLevel <= LogLevel.Error) { LogHelper.LogError("Failed to grab key"); } return(null); } using (HMACSHA256 hmac = new HMACSHA256(key)) { byte[] computedHmac = hmac.ComputeHash(outStream.GetBuffer(), 0, (int)outStream.Length); outStream.Position = hmacWritePos; outStream.Write(computedHmac, 0, computedHmac.Length); } } } else { #endif outWriter.WriteBits(messageType, 6); outStream.Write(messageBody.GetBuffer(), 0, (int)messageBody.Length); #if !DISABLE_CRYPTOGRAPHY } #endif } return(outStream); } catch (Exception e) { if (LogHelper.CurrentLogLevel <= LogLevel.Normal) { LogHelper.LogError("Error while wrapping headers"); } if (LogHelper.CurrentLogLevel <= LogLevel.Error) { LogHelper.LogError(e.ToString()); } return(null); } }