React Native
React Native
Encrypt File in Chunks using AES CBC
See more Encryption Examples
Demonstrates how to use the FirstChunk/LastChunk properties to encrypt a file chunk-by-chunk.Chilkat React Native Downloads
import { BinData, Crypt2, FileAccess } 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 crypt = new Crypt2();
crypt.cryptAlgorithm = 'aes';
crypt.cipherMode = 'cbc';
crypt.keyLength = 256;
crypt.setEncodedKey('000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F', 'hex');
crypt.setEncodedIV('000102030405060708090A0B0C0D0E0F', 'hex');
const fileToEncrypt = 'qa_data/hamlet.xml';
const facIn = new FileAccess();
try {
facIn.openForRead(fileToEncrypt);
} catch {
console.log('Failed to open file that is to be encrytped.');
return;
}
const outputEncryptedFile = 'c:/temp/qa_output/hamlet.enc';
const facOutEnc = new FileAccess();
try {
facOutEnc.openForWrite(outputEncryptedFile);
} catch {
console.log('Failed to encrypted output file.');
return;
}
// Let's encrypt in 10000 byte chunks.
const chunkSize = 10000;
const numChunks = facIn.getNumBlocks(chunkSize);
crypt.firstChunk = true;
crypt.lastChunk = false;
const bd = new BinData();
let i = 0;
while (i < numChunks) {
i++;
if (i === numChunks) {
crypt.lastChunk = true;
}
// Read the next chunk from the file.
// The last chunk will be whatever amount remains in the file..
bd.clear();
facIn.fileReadBd(chunkSize, bd);
// Encrypt.
crypt.encryptBd(bd);
// Write the encrypted chunk to the output file.
facOutEnc.fileWriteBd(bd, 0, 0);
crypt.firstChunk = false;
}
// Make sure both FirstChunk and LastChunk are restored to true after
// encrypting or decrypting in chunks. Otherwise subsequent encryptions/decryptions
// will produce unexpected results.
crypt.firstChunk = true;
crypt.lastChunk = true;
facIn.fileClose();
facOutEnc.fileClose();
// Decrypt the encrypted output file in a single call using CBC mode:
const decryptedFile = 'qa_output/hamlet_dec.xml';
await crypt.ckDecryptFileAsync(outputEncryptedFile, decryptedFile);
// Assume success for the example..
// Compare the contents of the decrypted file with the original file:
const bSame = facIn.fileContentsEqual(fileToEncrypt, decryptedFile);
console.log(`bSame = ${bSame}`);
}