DaGenix / rust-crypto

A (mostly) pure-Rust implementation of various cryptographic algorithms.
Apache License 2.0
1.4k stars 297 forks source link

AES 256, I try use example encrypt and decrypt, but decrypt always get error #450

Closed freehere107 closed 5 years ago

freehere107 commented 5 years ago

I use AES 256 Encryto text abcdef with key abc and iv hex caa7a5a622540ff30f098f2217b1e3be'get encryto text 41cbfec95ef76397cdcb81e037144a5c but use same params to decrypt always get error.

   0: std::sys::unix::backtrace::tracing::imp::unwind_backtrace
             at src/libstd/sys/unix/backtrace/tracing/gcc_s.rs:39
   1: std::sys_common::backtrace::_print
             at src/libstd/sys_common/backtrace.rs:71
   2: std::panicking::default_hook::{{closure}}
             at src/libstd/sys_common/backtrace.rs:59
             at src/libstd/panicking.rs:197
   3: std::panicking::default_hook
             at src/libstd/panicking.rs:211
   4: <std::panicking::begin_panic::PanicPayload<A> as core::panic::BoxMeUp>::get
             at src/libstd/panicking.rs:474
   5: std::panicking::continue_panic_fmt
             at src/libstd/panicking.rs:381
   6: std::panicking::try::do_call
             at src/libstd/panicking.rs:308
   7: <T as core::any::Any>::type_id
             at src/libcore/panicking.rs:85
   8: <T as core::any::Any>::type_id
             at src/libcore/panicking.rs:49
   9: time::PreciseTime::to
             at /rustc/237bf3244fffef501cf37d4bda00e1fce3fcfb46/src/libcore/macros.rs:12
  10: <reqwest::error::Kind as core::convert::From<serde_json::error::Error>>::from
             at src/wallet/mod.rs:639

And I decrypt with this function

pub fn decrypt(
    encrypted_data: &[u8],
    key: &[u8],
    iv: &[u8],
) -> Result<Vec<u8>, symmetriccipher::SymmetricCipherError> {
    let mut decryptor =
        aes::cbc_decryptor(aes::KeySize::KeySize256, key, iv, blockmodes::PkcsPadding);

    let mut final_result = Vec::<u8>::new();
    let mut read_buffer = buffer::RefReadBuffer::new(encrypted_data);
    let mut buffer = [0; 4096];
    let mut write_buffer = buffer::RefWriteBuffer::new(&mut buffer);

    loop {
        let result = decryptor.decrypt(&mut read_buffer, &mut write_buffer, true)?;
        final_result.extend(
            write_buffer
                .take_read_buffer()
                .take_remaining()
                .iter()
                .map(|&i| i),
        );
        match result {
            BufferResult::BufferUnderflow => break,
            BufferResult::BufferOverflow => {}
        }
    }

    Ok(final_result)
}
newpavlov commented 5 years ago

rust-crypto is unmaintained, check out RustCrypto crates, in particular read RustCrypto/block-ciphers README for AES-CBC example.

freehere107 commented 5 years ago

@newpavlov Thank you