Sample code for 30+ languages & platforms
React Native

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 React Native Downloads

React Native
import { Compression, Crypt2, JsonObject } from '@chilkat/react-native'

async function chilkatExample() {
  // This example assumes the Chilkat API to have been previously unlocked.
  // See Global Unlock Sample for sample code.

  const compress = new Compression();
  compress.algorithm = '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.
  const json = new JsonObject();
  json.updateString('cryptAlgorithm', 'aes');
  json.updateString('cipherMode', 'cbc');
  json.updateInt('keyLength', 128);
  json.updateInt('paddingScheme', 0);
  json.updateString('encodedIV', '000102030405060708090A0B0C0D0E0F');
  json.updateString('encodedKey', '000102030405060708090A0B0C0D0E0F');

  // Do file-to-file compression+encryption in a single call.
  const inPath = 'qa_data/largeFile.dat';
  const outPath = 'c:/temp/qa_output/compressed_encrypted.dat';
  try {
    await compress.compressEncryptFileAsync(json, inPath, outPath);
  } catch {
    console.log(compress.lastErrorText);
    return;
  }

  // We can do file-to-file decrypt/decompress like this:
  const inPath2 = outPath;
  const outPath2 = 'c:/temp/qa_output/restored.dat';
  try {
    await compress.decryptDecompressFileAsync(json, inPath2, outPath2);
  } catch {
    console.log(compress.lastErrorText);
    return;
  }

  // Note: The above decrypt + decompress is the equivalent of doing the same in these two steps:
  const crypt = new Crypt2();
  crypt.cryptAlgorithm = 'aes';
  crypt.cipherMode = 'cbc';
  crypt.keyLength = 128;
  crypt.paddingScheme = 0;
  crypt.setEncodedIV('000102030405060708090A0B0C0D0E0F', 'hex');
  crypt.setEncodedKey('000102030405060708090A0B0C0D0E0F', 'hex');

  const decryptedPath = 'c:/temp/qa_output/decrypted.dat';
  try {
    await crypt.ckDecryptFileAsync(inPath2, decryptedPath);
  } catch {
    console.log(crypt.lastErrorText);
    return;
  }

  const outPath3 = 'c:/temp/qa_output/restored_in_two_steps.dat';
  try {
    await compress.decompressFileAsync(decryptedPath, outPath3);
  } catch {
    console.log(compress.lastErrorText);
    return;
  }

  console.log('Success.');
}