Skip to content

Instantly share code, notes, and snippets.

@jordanbtucker
Last active September 13, 2017 14:46
Show Gist options
  • Save jordanbtucker/bf32e0f72a60bc1f8cefcf316234fbcf to your computer and use it in GitHub Desktop.
Save jordanbtucker/bf32e0f72a60bc1f8cefcf316234fbcf to your computer and use it in GitHub Desktop.
// Endpoint info excluded.
TcpClient client = new TcpClient();
var stream = client.GetStream();
// Assume pre-shared keys are used and set at this point.
AesManaged aes = new AesManaged();
var aesEncryptor = aes.CreateEncryptor();
CryptoStream aesStream = new CryptoStream(
stream, aesEncryptor, CryptoStreamMode.Write);
// Assume pre-shared keys here too.
HMACSHA256 mac = new HMACSHA256();
CryptoStream macStream = new CryptoStream(
aesStream, mac, CryptoStreamMode.Write);
// Assume a message with actual data is written to the macStream
// which updates the hash of the HMAC and also pipes the message
// to the aesStream which encrypts the data and writes it to the
// TCP socket stream.
byte[] message = new byte[1024];
macStream.Write(message, 0, message.Length);
// Flushing the final block of the aesStream also flushes the
// final block of the macStream, so we can append the signature
// to the stream unencrypted.
aesStream.FlushFinalBlock();
stream.Write(mac.Hash, 0, mac.Hash.Length);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment