Sample code for 30+ languages & platforms
Unicode C++

Compress and Encrypt a Large File (Low and Constant Memory Footprint)

See more Compression Examples

Demonstrates how to compress and encrypt a large file such that the memory footprint remains low and constant.

Note: This example requires Chilkat v9.5.0.99 or greater.

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkCompressionW.h>
#include <CkJsonObjectW.h>
#include <CkCrypt2W.h>

void ChilkatSample(void)
    {
    bool success = false;

    // This example assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    CkCompressionW compress;
    compress.put_Algorithm(L"deflate");

    // Set encryption params.
    // The possible values are the same as for the corresponding properties in the Chilkat Crypt2 class/object.
    // The encoded IV and Key must be specified as hex.
    CkJsonObjectW json;
    json.UpdateString(L"cryptAlgorithm",L"aes");
    json.UpdateString(L"cipherMode",L"cbc");
    json.UpdateInt(L"keyLength",128);
    json.UpdateInt(L"paddingScheme",0);
    json.UpdateString(L"encodedIV",L"000102030405060708090A0B0C0D0E0F");
    json.UpdateString(L"encodedKey",L"000102030405060708090A0B0C0D0E0F");

    // Do file-to-file compression+encryption in a single call.
    const wchar_t *inPath = L"qa_data/largeFile.dat";
    const wchar_t *outPath = L"c:/temp/qa_output/compressed_encrypted.dat";
    success = compress.CompressEncryptFile(json,inPath,outPath);
    if (success == false) {
        wprintf(L"%s\n",compress.lastErrorText());
        return;
    }

    // We can do file-to-file decrypt/decompress like this:
    const wchar_t *inPath2 = outPath;
    const wchar_t *outPath2 = L"c:/temp/qa_output/restored.dat";
    success = compress.DecryptDecompressFile(json,inPath2,outPath2);
    if (success == false) {
        wprintf(L"%s\n",compress.lastErrorText());
        return;
    }

    // Note: The above decrypt + decompress is the equivalent of doing the same in these two steps:
    CkCrypt2W crypt;
    crypt.put_CryptAlgorithm(L"aes");
    crypt.put_CipherMode(L"cbc");
    crypt.put_KeyLength(128);
    crypt.put_PaddingScheme(0);
    crypt.SetEncodedIV(L"000102030405060708090A0B0C0D0E0F",L"hex");
    crypt.SetEncodedKey(L"000102030405060708090A0B0C0D0E0F",L"hex");

    const wchar_t *decryptedPath = L"c:/temp/qa_output/decrypted.dat";
    success = crypt.CkDecryptFile(inPath2,decryptedPath);
    if (success == false) {
        wprintf(L"%s\n",crypt.lastErrorText());
        return;
    }

    const wchar_t *outPath3 = L"c:/temp/qa_output/restored_in_two_steps.dat";
    success = compress.DecompressFile(decryptedPath,outPath3);
    if (success == false) {
        wprintf(L"%s\n",compress.lastErrorText());
        return;
    }

    wprintf(L"Success.\n");
    }