Sample code for 30+ languages & platforms
Rust

Streaming Encryption by Encrypting in Chunks

See more Encryption Examples

Encrypt data in chunks.

Chilkat Rust Downloads

Rust
// This example requires 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(128);

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

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

let sb_encrypted = chilkat::StringBuilder::new();

// 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.)
crypt.set_first_chunk(true);
crypt.set_last_chunk(false);
let _ = sb_encrypted.append(&crypt.encrypt_string_enc(&txt1).unwrap_or_default());

// Encrypt the 2nd chunk
crypt.set_first_chunk(false);
crypt.set_last_chunk(false);
let _ = sb_encrypted.append(&crypt.encrypt_string_enc(&txt2).unwrap_or_default());

// 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...
crypt.set_first_chunk(false);
crypt.set_last_chunk(false);
for i in 0..=4 {
    let _ = sb_encrypted.append(&crypt.encrypt_string_enc(&txt1).unwrap_or_default());
    let _ = sb_encrypted.append(&crypt.encrypt_string_enc(&txt2).unwrap_or_default());
}

// Now encrypt the last chunk:
crypt.set_first_chunk(false);
crypt.set_last_chunk(true);
let _ = sb_encrypted.append(&crypt.encrypt_string_enc(&txt3).unwrap_or_default());

println!("{}", sb_encrypted.get_as_string().unwrap_or_default());

// Now decrypt in one call.
// (The data we're decrypting is both the first AND last chunk.)  
crypt.set_first_chunk(true);
crypt.set_last_chunk(true);
let decrypted_text = crypt.decrypt_string_enc(&sb_encrypted.get_as_string().unwrap_or_default()).unwrap_or_default();

println!("{}", decrypted_text);

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