I'm trying to encrypt a very basic string. I simply want to see what the encrypted string looks like before I send it over the network. However, I cannot seem to display the encrypted string. Here is my code, could somebody please direct me?
string data = "Hello World";
// Create the stream to write the encrypted data to
MemoryStream memoryStream = new MemoryStream();
ASCIIEncoding encoder = new ASCIIEncoding();
// Encrypt the data via Triple-DES before sending
TripleDESCryptoServiceProvider cryptoProvider = new TripleDESCryptoServiceProvider();
CryptoStream cryptoStream = new CryptoStream(memoryStream,
StreamWriter streamWriter = new StreamWriter(memoryStream);
// Read the encrypted string out loud
StreamReader streamReader = new StreamReader(memoryStream);
You need to flush final block on the crypto stream.
The crypto stream is buffered, so to write it to the underlying stream, it needs to be flushed. But in addition, whenever you are finished encrypting something with a block cipher using crypto stream, you must flush the final block, which adds the necessary padding to the end of the encrypted data and also flushes the stream. Otherwise, you get no data (or incomplete data) in the underlying stream.