none
Cryptography

    Question

  •  

    Hello,

     

    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?

     

    Code Block

    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,

      cryptoProvider.CreateEncryptor(encoder.GetBytes("13F19A1CD13F213A"),

      encoder.GetBytes("1514093415318823725123")), CryptoStreamMode.Write);

    StreamWriter streamWriter = new StreamWriter(memoryStream);

    streamWriter.WriteLine(data);

     

    // Read the encrypted string out loud

    StreamReader streamReader = new StreamReader(memoryStream);

    memoryStream.Seek(0, SeekOrigin.Begin);

    MessageBox.Show("Sending: " + streamReader.ReadToEnd());

     

     

    Thank you,

    Bill

    Wednesday, October 03, 2007 7:57 PM

Answers

  •  

    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.

    Wednesday, October 03, 2007 9:24 PM