Sample code for 30+ languages & platforms
C

Streaming Encryption by Encrypting in Chunks

See more Encryption Examples

Encrypt data in chunks.

Chilkat C Downloads

C
#include <C_CkCrypt2.h>
#include <C_CkStringBuilder.h>

void ChilkatSample(void)
    {
    HCkCrypt2 crypt;
    const char *txt1;
    const char *txt2;
    const char *txt3;
    HCkStringBuilder sbEncrypted;
    int i;
    const char *decryptedText;

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

    crypt = CkCrypt2_Create();

    CkCrypt2_putCryptAlgorithm(crypt,"aes");
    CkCrypt2_putCipherMode(crypt,"cbc");
    CkCrypt2_putKeyLength(crypt,128);

    CkCrypt2_SetEncodedKey(crypt,"000102030405060708090A0B0C0D0E0F","hex");
    CkCrypt2_SetEncodedIV(crypt,"000102030405060708090A0B0C0D0E0F","hex");

    CkCrypt2_putEncodingMode(crypt,"hex");
    txt1 = "The quick brown fox jumped over the lazy dog.\r\n";
    txt2 = "-\r\n";
    txt3 = "Done.\r\n";

    sbEncrypted = CkStringBuilder_Create();

    // Encrypt the 1st chunk:
    // (don't worry about feeding the data to the encryptor in 
    // exact multiples of the encryption algorithm's block size.
    // Chilkat will buffer the data.)
    CkCrypt2_putFirstChunk(crypt,TRUE);
    CkCrypt2_putLastChunk(crypt,FALSE);
    CkStringBuilder_Append(sbEncrypted,CkCrypt2_encryptStringENC(crypt,txt1));

    // Encrypt the 2nd chunk
    CkCrypt2_putFirstChunk(crypt,FALSE);
    CkCrypt2_putLastChunk(crypt,FALSE);
    CkStringBuilder_Append(sbEncrypted,CkCrypt2_encryptStringENC(crypt,txt2));

    // Now encrypt N more chunks...
    // Remember -- we're doing this in CBC mode, so each call
    // to the encrypt method depends on the state from previous
    // calls...
    CkCrypt2_putFirstChunk(crypt,FALSE);
    CkCrypt2_putLastChunk(crypt,FALSE);

    for (i = 0; i <= 4; i++) {
        CkStringBuilder_Append(sbEncrypted,CkCrypt2_encryptStringENC(crypt,txt1));
        CkStringBuilder_Append(sbEncrypted,CkCrypt2_encryptStringENC(crypt,txt2));
    }

    // Now encrypt the last chunk:
    CkCrypt2_putFirstChunk(crypt,FALSE);
    CkCrypt2_putLastChunk(crypt,TRUE);
    CkStringBuilder_Append(sbEncrypted,CkCrypt2_encryptStringENC(crypt,txt3));

    printf("%s\n",CkStringBuilder_getAsString(sbEncrypted));

    // Now decrypt in one call.
    // (The data we're decrypting is both the first AND last chunk.)  
    CkCrypt2_putFirstChunk(crypt,TRUE);
    CkCrypt2_putLastChunk(crypt,TRUE);
    decryptedText = CkCrypt2_decryptStringENC(crypt,CkStringBuilder_getAsString(sbEncrypted));

    printf("%s\n",decryptedText);

    // Note: You may decrypt in N chunks by setting the FirstChunk
    // and LastChunk properties prior to calling the Decrypt* methods


    CkCrypt2_Dispose(crypt);
    CkStringBuilder_Dispose(sbEncrypted);

    }