1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
//! Read/Write Wrapper for AES Encryption and Decryption during I/O Operations //! //! This crate provides an [`AesWriter`](struct.AesWriter.html), which can be used to wrap any //! existing [`Write`](https://doc.rust-lang.org/std/io/trait.Write.html) implementation with AES //! encryption, and [`AesReader`](struct.AesReader.html), which can wrap any existing //! [`Read`](https://doc.rust-lang.org/std/io/trait.Read.html) implemntation with AES decryption. //! If the inner reader provides a [`Seek`](https://doc.rust-lang.org/std/io/trait.Seek.html) //! implementation, AesReader will do so as well. //! See their struct-level documentation for more information. //! //! In fact this crate is not limited to AES. //! It can wrap any kind of [`BlockEncryptor`][be] i.e. [`BlockDecryptor`][bd] with CBC. //! //! [be]: https://docs.rs/rust-crypto/0.2.36/crypto/symmetriccipher/trait.BlockEncryptor.html //! [bd]: https://docs.rs/rust-crypto/0.2.36/crypto/symmetriccipher/trait.BlockEncryptor.html //! //! # Examples //! //! You can use [`AesWriter`](struct.AesWriter.html) to wrap a file with encryption. //! //! ```no_run //! # extern crate crypto; //! # extern crate aesstream; //! # use std::io::{Write, Result}; //! # use std::fs::File; //! # use crypto::aessafe::AesSafe128Encryptor; //! # use aesstream::AesWriter; //! # fn foo() -> Result<()> { //! let key = [0u8; 16]; //! let iv = vec![0u8; 16]; //! let file = File::open("...")?; //! let encryptor = AesSafe128Encryptor::new(&key); //! let mut writer = AesWriter::new(file, encryptor, iv.clone()); //! writer.write_all("Hello World!".as_bytes())?; //! # Ok(()) //! # } //! # fn main() { let _ = foo(); } //! ``` //! //! And [`AesReader`](struct.AesReader.html) to decrypt it again. //! //! ```no_run //! # extern crate crypto; //! # extern crate aesstream; //! # use std::io::{Read, Result}; //! # use std::fs::File; //! # use crypto::aessafe::AesSafe128Decryptor; //! # use aesstream::AesReader; //! # fn foo() -> Result<()> { //! let key = [0u8; 16]; //! let iv = vec![0u8; 16]; //! let file = File::open("...")?; //! let decryptor = AesSafe128Decryptor::new(&key); //! let mut reader = AesReader::new(file, decryptor, iv.clone()); //! let mut decrypted = String::new(); //! reader.read_to_string(&mut decrypted)?; //! assert_eq!(decrypted, "Hello World!"); //! # Ok(()) //! # } //! # fn main() { let _ = foo(); } //! ``` //! //! They can be used to en- and decrypt in-memory as well. //! //! ``` //! # extern crate crypto; //! # extern crate aesstream; //! # use std::io::{Read, Write, Result, Cursor}; //! # use crypto::aessafe::{AesSafe128Encryptor, AesSafe128Decryptor}; //! # use aesstream::{AesWriter, AesReader}; //! # fn foo() -> Result<()> { //! let key = [0u8; 16]; //! let iv = vec![0u8; 16]; //! let encryptor = AesSafe128Encryptor::new(&key); //! let mut writer = AesWriter::new(Vec::new(), encryptor, iv.clone()); //! writer.write_all("Hello World!".as_bytes())?; //! let encrypted = writer.into_inner()?; //! //! let decryptor = AesSafe128Decryptor::new(&key); //! let mut reader = AesReader::new(Cursor::new(encrypted), decryptor, iv); //! let mut decrypted = String::new(); //! reader.read_to_string(&mut decrypted)?; //! assert_eq!(decrypted, "Hello World!"); //! # Ok(()) //! # } //! # fn main() { let _ = foo(); } //! ``` extern crate crypto; #[cfg(test)] mod tests; use std::io::{Read, Write, Seek, SeekFrom, Result, Error, ErrorKind}; use crypto::symmetriccipher::{BlockDecryptor, BlockEncryptor, Encryptor, Decryptor}; use crypto::blockmodes::{PkcsPadding, CbcEncryptor, CbcDecryptor, EncPadding, DecPadding}; use crypto::buffer::{RefReadBuffer, RefWriteBuffer, BufferResult, WriteBuffer, ReadBuffer}; const BUFFER_SIZE: usize = 8192; /// Wraps a [`Write`](https://doc.rust-lang.org/std/io/trait.Write.html) implementation with CBC /// based on given [`BlockEncryptor`][be] /// /// [be]: https://docs.rs/rust-crypto/0.2.36/crypto/symmetriccipher/trait.BlockEncryptor.html /// /// # Examples /// /// Write encrypted to a file. /// /// ```no_run /// # extern crate crypto; /// # extern crate aesstream; /// # use std::io::{Write, Result}; /// # use std::fs::File; /// # use crypto::aessafe::AesSafe128Encryptor; /// # use aesstream::AesWriter; /// # fn foo() -> Result<()> { /// let key = [0u8; 16]; /// let iv = vec![0u8; 16]; /// let file = File::open("...")?; /// let encryptor = AesSafe128Encryptor::new(&key); /// let mut writer = AesWriter::new(file, encryptor, iv); /// writer.write_all("Hello World!".as_bytes())?; /// # Ok(()) /// # } /// # fn main() { let _ = foo(); } /// ``` /// /// Encrypt in-memory. /// /// ``` /// # extern crate crypto; /// # extern crate aesstream; /// # use std::io::{Write, Result, Cursor}; /// # use crypto::aessafe::AesSafe128Encryptor; /// # use aesstream::AesWriter; /// # fn foo() -> Result<()> { /// let key = [0u8; 16]; /// let iv = vec![0u8; 16]; /// let encryptor = AesSafe128Encryptor::new(&key); /// let mut writer = AesWriter::new(Vec::new(), encryptor, iv); /// writer.write_all("Hello World!".as_bytes())?; /// let encrypted = writer.into_inner()?; /// # Ok(()) /// # } /// # fn main() { let _ = foo(); } /// ``` pub struct AesWriter<E: BlockEncryptor, W: Write> { /// Writer to write encrypted data to writer: Option<W>, /// Encryptor to encrypt data with enc: CbcEncryptor<E, EncPadding<PkcsPadding>>, /// Indicates weather the encryptor has done its final operation (inserting padding) closed: bool, } impl<E: BlockEncryptor, W: Write> AesWriter<E, W> { /// Creates a new AesWriter. /// /// # Parameters /// /// * **writer**: Writer to write encrypted data into /// * **enc**: [`BlockEncryptor`][be] to use for encyrption /// * **iv**: IV used for CBC operation. It must have a length of 16 bytes /// /// # Panics /// /// Panics if the passed IV does not have 16 bytes. /// /// # Examples /// /// ```no_run /// # extern crate crypto; /// # extern crate aesstream; /// # use crypto::aessafe::AesSafe128Encryptor; /// # use std::io::Result; /// # use std::fs::File; /// # use aesstream::AesWriter; /// # fn foo() -> Result<()> { /// let key = [0u8; 16]; /// let iv = vec![0u8; 16]; /// let encryptor = AesSafe128Encryptor::new(&key); /// let file = File::open("...")?; /// let mut writer = AesWriter::new(file, encryptor, iv); /// # Ok(()) /// # } /// # fn main() { let _ = foo(); } /// ``` /// /// [be]: https://docs.rs/rust-crypto/0.2.36/crypto/symmetriccipher/trait.BlockEncryptor.html pub fn new(writer: W, enc: E, iv: Vec<u8>) -> AesWriter<E, W> { assert_eq!(iv.len(), 16, "IV must be 16 bytes in length"); AesWriter { writer: Some(writer), enc: CbcEncryptor::new(enc, PkcsPadding, iv), closed: false, } } /// Consumes self and returns the underlying writer. /// /// This method finishes encryption and flushes the internal encryption buffer. /// /// # Errors /// /// If flushing fails, the error is returned. /// /// # Examples /// /// ```no_run /// # extern crate crypto; /// # extern crate aesstream; /// # use crypto::aessafe::AesSafe128Encryptor; /// # use std::io::Result; /// # use std::fs::File; /// # use aesstream::AesWriter; /// # fn foo() -> Result<()> { /// let key = [0u8; 16]; /// let iv = vec![0u8; 16]; /// let encryptor = AesSafe128Encryptor::new(&key); /// let file = File::open("...")?; /// let mut writer = AesWriter::new(file, encryptor, iv); /// // do something with writer /// let file = writer.into_inner()?; /// # Ok(()) /// # } /// # fn main() { let _ = foo(); } /// ``` pub fn into_inner(mut self) -> Result<W> { self.flush()?; Ok(self.writer.take().unwrap()) } /// Encrypts passed buffer and writes all resulting encrypted blocks to the underlying writer /// /// # Parameters /// /// * **buf**: Plaintext to encrypt and write /// * **eof**: If the provided buf is the last one to come and therefore encryption should be /// finished and padding added. fn encrypt_write(&mut self, buf: &[u8], eof: bool) -> Result<usize> { let mut read_buf = RefReadBuffer::new(buf); let mut out = [0u8; BUFFER_SIZE]; let mut write_buf = RefWriteBuffer::new(&mut out); loop { let res = self.enc.encrypt(&mut read_buf, &mut write_buf, eof) .map_err(|e| Error::new(ErrorKind::Other, format!("encryption error: {:?}", e)))?; let mut enc = write_buf.take_read_buffer(); let enc = enc.take_remaining(); self.writer.as_mut().unwrap().write_all(enc)?; match res { BufferResult::BufferUnderflow => break, BufferResult::BufferOverflow if eof => panic!("read_buf underflow during encryption with eof"), BufferResult::BufferOverflow => {}, } } // CbcEncryptor has its own internal buffer and always consumes all input assert_eq!(read_buf.remaining(), 0); Ok(buf.len()) } } impl<E: BlockEncryptor, W: Write> Write for AesWriter<E, W> { /// Encrypts the passed buffer and writes the result to the underlying writer. /// /// Due to the blocksize of CBC not all data will be written instantaneously. /// For example if 17 bytes are passed, the first 16 will be encrypted as one block and written /// the underlying writer, but the last byte won't be encrypted and written yet. /// /// If [`flush`](#method.flush) has been called, this method will always return an error. fn write(&mut self, buf: &[u8]) -> Result<usize> { if self.closed { return Err(Error::new(ErrorKind::Other, "AesWriter is closed")); } let written = self.encrypt_write(buf, false)?; Ok(written) } /// Flush this output stream, ensuring that all intermediately buffered contents reach their destination. /// [Read more](https://doc.rust-lang.org/nightly/std/io/trait.Write.html#tymethod.flush) /// /// **Warning**: When this method is called, the encryption will finish and insert final padding. /// After calling `flush`, this writer cannot be written to anymore and will always return an /// error. fn flush(&mut self) -> Result<()> { if self.closed { return Ok(()); } self.encrypt_write(&[], true)?; self.closed = true; self.writer.as_mut().unwrap().flush() } } impl<E: BlockEncryptor, W: Write> Drop for AesWriter<E, W> { /// Drops this AesWriter trying to finish encryption and to write everything to the underlying writer. fn drop(&mut self) { if self.writer.is_some() { if !std::thread::panicking() { self.flush().unwrap(); } else { let _ = self.flush(); } } } } /// Wraps a [`Read`](https://doc.rust-lang.org/std/io/trait.Read.html) implementation with CBC /// based on given [`BlockDecryptor`][bd] /// /// [bd]: https://docs.rs/rust-crypto/0.2.36/crypto/symmetriccipher/trait.BlockDecryptor.html /// /// # Examples /// /// Read encrypted file. /// /// ```no_run /// # extern crate crypto; /// # extern crate aesstream; /// # use std::io::{Read, Result}; /// # use std::fs::File; /// # use crypto::aessafe::AesSafe128Decryptor; /// # use aesstream::AesReader; /// # fn foo() -> Result<()> { /// let key = [0u8; 16]; /// let iv = vec![0u8; 16]; /// let file = File::open("...")?; /// let decryptor = AesSafe128Decryptor::new(&key); /// let mut reader = AesReader::new(file, decryptor, iv); /// let mut decrypted = Vec::new(); /// reader.read_to_end(&mut decrypted)?; /// # Ok(()) /// # } /// # fn main() { let _ = foo(); } /// ``` /// /// Decrypt in-memory. /// /// ``` /// # extern crate crypto; /// # extern crate aesstream; /// # use std::io::{Read, Result, Cursor}; /// # use std::fs::File; /// # use crypto::aessafe::AesSafe128Decryptor; /// # use aesstream::AesReader; /// # fn foo() -> Result<()> { /// let encrypted = vec![]; /// let key = [0u8; 16]; /// let iv = vec![0u8; 16]; /// let decryptor = AesSafe128Decryptor::new(&key); /// let mut reader = AesReader::new(Cursor::new(encrypted), decryptor, iv); /// let mut decrypted = Vec::new(); /// reader.read_to_end(&mut decrypted)?; /// # Ok(()) /// # } /// # fn main() { let _ = foo(); } /// ``` pub struct AesReader<D: BlockDecryptor, R: Read> { /// Reader to read encrypted data from reader: R, /// Decryptor to decrypt data with dec: CbcDecryptor<D, DecPadding<PkcsPadding>>, /// IV used if seeked to the first block iv: Vec<u8>, /// Block size of BlockDecryptor, needed when seeking to correctly seek to the nearest block block_size: usize, /// Buffer used to store blob needed to find out if we reached eof buffer: Vec<u8>, /// Indicates wheather eof of the underlying buffer was reached eof: bool, } impl<D: BlockDecryptor, R: Read> AesReader<D, R> { /// Creates a new AesReader. /// /// # Parameters /// /// * **reader**: Reader to read encrypted data from /// * **dec**: [`BlockDecryptor`][be] to use for decyrption /// * **iv**: IV used for CBC operation. It must have a length of 16 bytes /// /// # Panics /// /// Panics if the passed IV does not have 16 bytes. /// /// # Examples /// /// ```no_run /// # extern crate crypto; /// # extern crate aesstream; /// # use crypto::aessafe::AesSafe128Decryptor; /// # use std::io::Result; /// # use std::fs::File; /// # use aesstream::AesReader; /// # fn foo() -> Result<()> { /// let key = [0u8; 16]; /// let iv = vec![0u8; 16]; /// let decryptor = AesSafe128Decryptor::new(&key); /// let file = File::open("...")?; /// let mut reader = AesReader::new(file, decryptor, iv); /// # Ok(()) /// # } /// # fn main() { let _ = foo(); } /// ``` /// /// [be]: https://docs.rs/rust-crypto/0.2.36/crypto/symmetriccipher/trait.BlockEncryptor.html pub fn new(reader: R, dec: D, iv: Vec<u8>) -> AesReader<D, R> { assert_eq!(iv.len(), 16, "IV must be 16 bytes in length"); AesReader { reader: reader, block_size: dec.block_size(), iv: iv.clone(), dec: CbcDecryptor::new(dec, PkcsPadding, iv), buffer: Vec::new(), eof: false, } } /// Consumes self and returns the underlying reader. /// /// This method **does not** finish decryption and / or process padding. /// /// # Examples /// /// ```no_run /// # extern crate crypto; /// # extern crate aesstream; /// # use crypto::aessafe::AesSafe128Decryptor; /// # use std::io::Result; /// # use std::fs::File; /// # use aesstream::AesReader; /// # fn foo() -> Result<()> { /// let key = [0u8; 16]; /// let iv = vec![0u8; 16]; /// let decryptor = AesSafe128Decryptor::new(&key); /// let file = File::open("...")?; /// let mut reader = AesReader::new(file, decryptor, iv); /// // do something with reader /// let file = reader.into_inner(); /// # Ok(()) /// # } /// # fn main() { let _ = foo(); } /// ``` pub fn into_inner(self) -> R { self.reader } /// Reads at max BUFFER_SIZE bytes, handles potential eof and returns the buffer as Vec<u8> fn fill_buf(&mut self) -> Result<Vec<u8>> { let mut eof_buffer = vec![0u8; BUFFER_SIZE]; let read = self.reader.read(&mut eof_buffer)?; self.eof = read == 0; eof_buffer.truncate(read); Ok(eof_buffer) } /// Reads and decrypts data from the underlying stream and writes it into the passed buffer. /// /// The CbcDecryptor has an internal output buffer, but not an input buffer. /// Therefore, we need to take care of letfover input. /// Additionally, we need to handle eof correctly, as CbcDecryptor needs to correctly interpret /// padding. /// Thus, we need to read 2 buffers. The first one is read as input for decryption and the second /// one to determine if eof is reached. /// The next time this function is called, the second buffer is passed as input into decryption /// and the first buffer is filled to find out if we reached eof. /// /// # Parameters /// /// * **buf**: Buffer to write decrypted data into. fn read_decrypt(&mut self, buf: &mut [u8]) -> Result<usize> { // if this is the first iteration, fill internal buffer if self.buffer.is_empty() && !self.eof { self.buffer = self.fill_buf()?; } let buf_len = buf.len(); let mut write_buf = RefWriteBuffer::new(buf); let res; let remaining; { let mut read_buf = RefReadBuffer::new(&self.buffer); // test if CbcDecryptor still has enough decrypted data or we have enough buffered res = self.dec.decrypt(&mut read_buf, &mut write_buf, self.eof) .map_err(|e| Error::new(ErrorKind::Other, format!("decryption error: {:?}", e)))?; remaining = read_buf.remaining(); } // keep remaining bytes let len = self.buffer.len(); self.buffer.drain(..(len - remaining)); // if we were able to decrypt, return early match res { BufferResult::BufferOverflow => return Ok(buf_len), BufferResult::BufferUnderflow if self.eof => return Ok(write_buf.position()), _ => {} } // else read new buffer let mut dec_len = 0; // We must return something, if we have something. // If the reader doesn't return enough so that we can decrypt a block, we need to continue // reading until we have enough data to return one decrypted block, or until we reach eof. // If we reach eof, we will be able to decrypt the final block because of padding. while dec_len == 0 && !self.eof { let eof_buffer = self.fill_buf()?; let remaining; { let mut read_buf = RefReadBuffer::new(&self.buffer); self.dec.decrypt(&mut read_buf, &mut write_buf, self.eof) .map_err(|e| Error::new(ErrorKind::Other, format!("decryption error: {:?}", e)))?; let mut dec = write_buf.take_read_buffer(); let dec = dec.take_remaining(); dec_len = dec.len(); remaining = read_buf.remaining(); } // keep remaining bytes let len = self.buffer.len(); self.buffer.drain(..(len - remaining)); // append newly read bytes self.buffer.extend(eof_buffer); } Ok(dec_len) } } impl<D: BlockDecryptor, R: Read> Read for AesReader<D, R> { /// Reads encrypted data from the underlying reader, decrypts it and writes the result into the /// passed buffer. fn read(&mut self, buf: &mut [u8]) -> Result<usize> { let read = self.read_decrypt(buf)?; Ok(read) } } impl<D: BlockDecryptor, R: Read + Seek> Seek for AesReader<D, R> { /// Seek to an offset, in bytes, in a stream. /// [Read more](https://doc.rust-lang.org/nightly/std/io/trait.Seek.html#tymethod.seek) /// /// When seeking, this reader takes care of reinitializing the CbcDecryptor with the correct IV. /// The passed position does *not* need to be aligned to the blocksize. fn seek(&mut self, pos: SeekFrom) -> Result<u64> { match pos { SeekFrom::Start(offset) => { let block_num = offset / self.block_size as u64; let block_offset = offset % self.block_size as u64; // reset CbcDecryptor if block_num == 0 { self.reader.seek(SeekFrom::Start(0))?; self.dec.reset(&self.iv); } else { self.reader.seek(SeekFrom::Start((block_num - 1) * self.block_size as u64))?; let mut iv = vec![0u8; self.block_size]; self.reader.read_exact(&mut iv)?; self.dec.reset(&iv); } self.buffer = Vec::new(); self.eof = false; let mut skip = vec![0u8; block_offset as usize]; self.read_exact(&mut skip)?; Ok(offset) }, SeekFrom::Current(_) | SeekFrom::End(_) => { let pos = self.reader.seek(pos)?; self.seek(SeekFrom::Start(pos)) }, } } }