Rust
Rust
Decrypt File in Chunks using 256-bit AES
See more Encryption Examples
Shows how to decrypt a file chunk-by-chunk using FirstChunk/LastChunk properties and accumulate the results in memory with a Chilkat BinData object.Chilkat Rust Downloads
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// This example decrypts the file previously encrypted in this example:
// Encrypt File in Chunks using AES CBC
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_decrypt = "c:/temp/qa_output/hamlet.enc".to_string();
let fac_in = chilkat::FileAccess::new();
if fac_in.open_for_read(&file_to_decrypt).is_err() {
println!("Failed to open file to be decrytped.");
return;
}
// Let's decrypt in 32000 byte chunks.
let chunk_size = 32000;
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 bd_decrypted = 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);
// Decrypt this chunk.
let _ = crypt.decrypt_bd(&bd);
// Accumulate the decrypted chunks.
let _ = bd_decrypted.append_bd(&bd);
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();
// The fully decrypted file is contained in bdDecrypted.
// You can save to a file if desired, or use the decrypted data in your application directly from bdDecrypted.
let _ = bd_decrypted.write_file("c:/temp/qa_output/hamlet_decrypted.xml");