Sample code for 30+ languages & platforms
Rust

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 Rust Downloads

Rust

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

let crypt = chilkat::Crypt2::new();

crypt.set_crypt_algorithm("aes");
crypt.set_cipher_mode("cbc");
crypt.set_key_length(256);

crypt.set_encoded_key("000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F", "hex");
crypt.set_encoded_iv("000102030405060708090A0B0C0D0E0F", "hex");

let file_to_encrypt = "qa_data/hamlet.xml".to_string();
let fac_in = chilkat::FileAccess::new();
if fac_in.open_for_read(&file_to_encrypt).is_err() {
    println!("Failed to open file that is to be encrytped.");
    return;
}

let output_encrypted_file = "c:/temp/qa_output/hamlet.enc".to_string();
let fac_out_enc = chilkat::FileAccess::new();
if fac_out_enc.open_for_write(&output_encrypted_file).is_err() {
    println!("Failed to encrypted output file.");
    return;
}

// Let's encrypt in 10000 byte chunks.
let chunk_size = 10000;
let num_chunks = fac_in.get_num_blocks(chunk_size);

crypt.set_first_chunk(true);
crypt.set_last_chunk(false);

let bd = chilkat::BinData::new();

let mut i = 0;
while i < num_chunks {
    i = i + 1;
    if i == num_chunks {
        crypt.set_last_chunk(true);
    }

    // Read the next chunk from the file.
    // The last chunk will be whatever amount remains in the file..
    let _ = bd.clear();
    let _ = fac_in.file_read_bd(chunk_size, &bd);

    // Encrypt.
    let _ = crypt.encrypt_bd(&bd);

    // Write the encrypted chunk to the output file.
    let _ = fac_out_enc.file_write_bd(&bd, 0, 0);

    crypt.set_first_chunk(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.set_first_chunk(true);
crypt.set_last_chunk(true);

fac_in.file_close();
fac_out_enc.file_close();

// Decrypt the encrypted output file in a single call using CBC mode:
let decrypted_file = "qa_output/hamlet_dec.xml".to_string();
let _ = crypt.ck_decrypt_file(&output_encrypted_file, &decrypted_file).is_ok();
// Assume success for the example..

// Compare the contents of the decrypted file with the original file:
let b_same = fac_in.file_contents_equal(&file_to_encrypt, &decrypted_file);
println!("bSame = {}", b_same);