How to handle RustCrypto errors?

Somehow the errors returned from RustCrypto functions are different from normal errors and cannot be handled by anyhow?

Cargo.toml:

[package]
name = "crypt-error-test"
version = "0.1.0"
edition = "2021"

[dependencies]
anyhow = "1.0.69"
chacha20poly1305 = "0.10.1"

main.rs:

use std::error::Error;
use anyhow::Result;
use chacha20poly1305::{
    aead::{Aead, AeadCore, KeyInit, OsRng},
    ChaCha20Poly1305
};

fn main() -> Result<(), Box<dyn Error>> {
    Ok(foo()?)
}

fn foo() -> Result<()> {
    // This is the example from https://docs.rs/chacha20poly1305/0.10.1/chacha20poly1305/index.html

    let key = ChaCha20Poly1305::generate_key(&mut OsRng);
    let cipher = ChaCha20Poly1305::new(&key);
    let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng); // 96-bits; unique per message
    let ciphertext = cipher.encrypt(&nonce, b"plaintext message".as_ref())?;
    let plaintext = cipher.decrypt(&nonce, ciphertext.as_ref())?;
    assert_eq!(&plaintext, b"plaintext message");
    Ok(())
}

This doesn't compile:

   Compiling crypt-error-test v0.1.0 (C:\dev-rust\crypto-error-test)
error[E0277]: the trait bound `chacha20poly1305::Error: std::error::Error` is not satisfied
  --> src\main.rs:16:75
   |
16 |     let ciphertext = cipher.encrypt(&nonce, b"plaintext message".as_ref())?;
   |                                                                           ^ the trait `std::error::Error` is not implemented for `chacha20poly1305::Error`
   |
   = help: the following other types implement trait `FromResidual<R>`:
             <Result<T, F> as FromResidual<Result<Infallible, E>>>
             <Result<T, F> as FromResidual<Yeet<E>>>
   = note: required for `anyhow::Error` to implement `From<chacha20poly1305::Error>`
   = note: required for `Result<(), anyhow::Error>` to implement `FromResidual<Result<Infallible, chacha20poly1305::Error>>`

Enable the std feature and it should work

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.