Skip to content

Commit

Permalink
README.md: use ? instead of expect` in example (#385)
Browse files Browse the repository at this point in the history
Using `?` encourages users to properly handle errors rather than
panicking.
  • Loading branch information
tarcieri authored Nov 20, 2023
1 parent 3eb4e38 commit 00eaa91
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,24 @@ A portable RSA implementation in pure Rust.
## Example

```rust
# fn main() -> Result<(), rsa::Error> {
use rsa::{Pkcs1v15Encrypt, RsaPrivateKey, RsaPublicKey};

let mut rng = rand::thread_rng();
let bits = 2048;
let priv_key = RsaPrivateKey::new(&mut rng, bits).expect("failed to generate a key");
let priv_key = RsaPrivateKey::new(&mut rng, bits)?;
let pub_key = RsaPublicKey::from(&priv_key);

// Encrypt
let data = b"hello world";
let enc_data = pub_key.encrypt(&mut rng, Pkcs1v15Encrypt, &data[..]).expect("failed to encrypt");
let enc_data = pub_key.encrypt(&mut rng, Pkcs1v15Encrypt, &data[..])?;
assert_ne!(&data[..], &enc_data[..]);

// Decrypt
let dec_data = priv_key.decrypt(Pkcs1v15Encrypt, &enc_data).expect("failed to decrypt");
let dec_data = priv_key.decrypt(Pkcs1v15Encrypt, &enc_data)?;
assert_eq!(&data[..], &dec_data[..]);
# Ok(())
# }
```

> **Note:** If you encounter unusually slow key generation time while using `RsaPrivateKey::new` you can try to compile in release mode or add the following to your `Cargo.toml`. Key generation is much faster when building with higher optimization levels, but this will increase the compile time a bit.
Expand Down

0 comments on commit 00eaa91

Please sign in to comment.