Closed nicolaspernoud closed 2 years ago
I'll have to look into the buffer size corruption issue because it seems like your code is fine at a first glance. However for the speed, note that cryptostream does not do any buffering (because it can return the underlying stream but doesn't necessarily consume everything it has read, so data would be lost otherwise) so you really should use it with a BufReader/BufWriter between it in and the source/destination. Can you see if that fixes your slowness issues?
I believe your issue with the decrypted content mismatch is caused by your use of .write(...)
instead of .write_all(...)
which is a common mistake with people make when using the rust Write
trait (and not related to the cryptostream
crate).
The slowness decrypting is not related to cryptostream
or even how it reads from the source stream; it's the writes to the plain rust std::io::File
(from the in-memory decrypted buffer) that introduce the biggest slowdown.
For a 100 MiB encrypted intermediate file, decrypting it with the following takes 13 seconds:
let enc_path = Path::new("encrypted.bin");
let dec_path = Path::new("decrypted.bin");
let encrypted = File::open(&enc_path).unwrap();
let mut decryptor = read::Decryptor::new(encrypted, Cipher::aes_128_cbc(), &key, &iv).unwrap();
let mut decrypted = File::create(&dec_path).unwrap();
let mut buffer = [0u8; 4096];
loop {
let read = decryptor.read(&mut buffer).unwrap();
decrypted.write_all(&buffer[..read]).unwrap();
if read == 0 {
break;
}
}
decrypted.flush.unwrap();
While adding just one line brings down the decryption speed to 1.3s:
let enc_path = Path::new("encrypted.bin");
let dec_path = Path::new("decrypted.bin");
let encrypted = File::open(&enc_path).unwrap();
let mut decryptor = read::Decryptor::new(encrypted, Cipher::aes_128_cbc(), &key, &iv).unwrap();
let mut decrypted = File::create(&dec_path).unwrap();
let mut decrypted = BufWriter::new(decrypted); // THIS LINE WAS ADDED
let mut buffer = [0u8; 4096];
loop {
let read = decryptor.read(&mut buffer).unwrap();
decrypted.write_all(&buffer[..read]).unwrap();
if read == 0 {
break;
}
}
decrypted.flush.unwrap();
Hello,
Ok, thanks a lot for your answers. The buffread (in my use case) and the write_all did it !
Hello, The following code, used with a quite big file (300 Mo) :