PowerTCP Zip Compression for .NET

from $299.00
Available Platforms

See all PowerTCP Zip Compression for .NET Code Examples

Encrypt Memory Streams Example

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

 

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);
}

 

The PowerTCP Zip Compression for .NET Compress a Folder example is included with a trial installation of PowerTCP Zip Compression for .NET. To download a trial please visit the PowerTCP Zip Compression for .NET product page.