C# Encrypting/Decrypting with Stream

This C# example demonstrates how to use Chilkat.Crypt2 to encrypt and decrypting using the .NET FileStream class:

    Chilkat.Crypt2 crypt = new Chilkat.Crypt2();
    bool success = crypt.UnlockComponent("Anything for 30-day trial");
    if (!success)
    {
        MessageBox.Show(crypt.LastErrorText);
        return;
    }

    crypt.CryptAlgorithm = "aes";
    crypt.CipherMode = "cbc";
    crypt.KeyLength = 128;

    crypt.SetEncodedIV("0000000000000000", "hex");
    crypt.SetEncodedKey("abcdefghijklmnop", "ascii");

    // Open input and output files as file streams...
    FileStream fsIn = File.OpenRead("hamlet.xml");
    FileStream fsOut = File.Create("encrypted.dat");

    crypt.FirstChunk = true;
    crypt.LastChunk = false;
    byte [] encryptedChunk;

    // Encrypt the stream in 1024 byte chunks.
    byte[] b = new byte[1024];

    int n;
    while ((n = fsIn.Read(b, 0, b.Length)) > 0)
    {
        if (n < b.Length)
        {
            // Don't encrypt the full 1024 bytes, only the amount read...
            byte[] tmp = new byte[n];
            int i;
            for (i = 0; i < n; i++) tmp[i] = b[i];
            encryptedChunk = crypt.EncryptBytes(tmp);
        }
        else
        {
            encryptedChunk = crypt.EncryptBytes(b);
        }

        fsOut.Write(encryptedChunk, 0, encryptedChunk.Length);
        crypt.FirstChunk = false;
    }
    fsIn.Close();

    // Flush any remaining encrypted data.
    crypt.LastChunk = true;
    byte[] empty = { };
    encryptedChunk = crypt.EncryptBytes(empty);
    if (encryptedChunk.Length > 0)
    {
        fsOut.Write(encryptedChunk, 0, encryptedChunk.Length);
    }
    fsOut.Close();


    // Now decrypt in chunks.  The decryptor must know when the last
    // block is being processed so it may unpad it correctly.

    System.IO.FileInfo fi = new System.IO.FileInfo("encrypted.dat");
    long fileSize = fi.Length;
    int numChunks = (int)fileSize / b.Length;

    fsIn = File.OpenRead("encrypted.dat");
    fsOut = File.Create("decrypted.xml");

    crypt.FirstChunk = true;
    crypt.LastChunk = false;
    byte[] decryptedChunk;

    int idx;
    for (idx = 0; idx <= numChunks; idx++)
    {
        n = fsIn.Read(b, 0, b.Length);

        // Is this the last chunk?
        if (idx == numChunks)
        {
            // Decrypt only the amount read...
            byte[] lastBlock = new byte[n];
            int i;
            for (i = 0; i < n; i++) lastBlock[i] = b[i];
            crypt.LastChunk = true;
            decryptedChunk = crypt.DecryptBytes(lastBlock);
        }
        else
        {
            decryptedChunk = crypt.DecryptBytes(b);
        }

        fsOut.Write(decryptedChunk, 0, decryptedChunk.Length);
        crypt.FirstChunk = false;
    }
    fsIn.Close();
    fsOut.Close();

    MessageBox.Show("Finished!");

C# 3DES (Triple-DES) Test Vector

This post provides C# sample code for matching a test vector (known answer test).

3DES Settings:

  • ECB Mode
  • 192-bit key (i.e. 3 8-bit keys)
  • ASCII Key Bytes: 1234567890123456ABCDEFGH
  • ASCII Text to Encrypt: The quick brown fox jumped over the lazy dog
  • Pads with zero bytes
  • Hexadecimalized Encrypted Result:
    13d4d3549493d2870f93c3e0812a06de467e1f9c0bfb16c0
    70ede5cabbd3ca62f217a7ae8d47f2c7bf62eb309323b58b


C# Code:

    string keyAscii = "1234567890123456ABCDEFGH";
    byte[] key = ASCIIEncoding.ASCII.GetBytes(keyAscii);

    byte[] clearText = ASCIIEncoding.ASCII.GetBytes("The quick brown fox jumped over the lazy dog");

    TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
    des.KeySize = 192;
    des.Key = key;
    des.Mode = CipherMode.ECB;
    des.Padding = PaddingMode.Zeros;
    byte[] cipherText = des.CreateEncryptor().TransformFinalBlock(clearText, 0, clearText.Length);

3DES Code to match this test vector in other languages:
ASP: 3DES Test Vector
SQL Server: 3DES Test Vector
C#: 3DES Test Vector
C++: 3DES Test Vector
MFC: 3DES Test Vector
C: 3DES Test Vector
Delphi: 3DES Test Vector
Visual FoxPro: 3DES Test Vector
Java: 3DES Test Vector
Perl: 3DES Test Vector
PHP: 3DES Test Vector
Python: 3DES Test Vector
Ruby: 3DES Test Vector
VB.NET: 3DES Test Vector
Visual Basic: 3DES Test Vector
VBScript: 3DES Test Vector