Version: 2.1.0.2
Easily add Zip capability to your .NET Windows or ASP.NET application without sacrificing power and flexibility.

Encrypt Memory Streams Code Example

The following example demonstrates compression and AES encryption of data in memory by utilizing the Stream interface of the archive component.

< Back to all samples for PowerTCP Zip Compression for .NET

private void buttonTest_Click(object sender, EventArgs e)
{
    //Test the encrypt and decrypt functions with a simple data string.
    string data = "Hello, this is my data to be encrypted!";
    string encryptedData = encrypt(data, "pass123!");
    string decryptedData = decrypt(encryptedData, "pass123!");
    MessageBox.Show("Original Data: " + decryptedData + Environment.NewLine +
        "Processed Data: " + decryptedData);
}

private string encrypt(string data, string password)
{
    //Write the data to a stream.
    byte[] buffer = System.Text.Encoding.Default.GetBytes(data);
    MemoryStream source = new MemoryStream(buffer);
    source.Position = 0;

    //Encrypt the data using AES 256.
    archive1.DefaultEncryption = Dart.PowerTCP.Zip.Encryption.Aes256Bit;
    archive1.Password = password;

    //Add the data to the archive.
    archive1.Clear();
    archive1.Add(source);

    //Compress and encrypt the data to a stream.
    MemoryStream result = new MemoryStream();
    archive1.Zip(result);

    //Read the stream to a buffer.
    result.Position = 0;
    buffer = new byte[result.Length];
    result.Read(buffer, 0, buffer.Length);

    //Return compressed and encrypted data as a string.
    //Note that smaller strings (with fewer than approx 200 bytes)
    //will not result in smaller strings due to zip overhead.
    return System.Text.Encoding.Default.GetString(buffer);
}

private string decrypt(string data, string password)
{
    //Write the data to a stream.
    byte[] buffer = System.Text.Encoding.Default.GetBytes(data);
    MemoryStream source = new MemoryStream(buffer);
    source.Position = 0;

    //Decrypt the data using AES 256.
    archive1.DefaultEncryption = Dart.PowerTCP.Zip.Encryption.Aes256Bit;
    archive1.Password = password;

    //Open the compressed and encrypted data in the archive.
    archive1.Clear();
    archive1.Open(source);

    //Decompress and decrypt data to a stream.
    MemoryStream result = new MemoryStream();
    archive1[0].Unzip(result);

    //Read the stream to a buffer.
    result.Position = 0;
    buffer = new byte[result.Length];
    result.Read(buffer, 0, buffer.Length);

    //Return decompressed and decrypted data as a string.
    return System.Text.Encoding.Default.GetString(buffer);
}