Skip to content

Commit 57956bf

Browse files
authored
aes-gcm: improve doc example (#493)
1 parent 6ac2d1c commit 57956bf

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

aes-gcm/src/lib.rs

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,33 @@
1212
//!
1313
//! Simple usage (allocating, no associated data):
1414
//!
15-
#![cfg_attr(all(feature = "getrandom", feature = "std"), doc = "```")]
16-
#![cfg_attr(not(all(feature = "getrandom", feature = "std")), doc = "```ignore")]
17-
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
15+
//! ```
1816
//! use aes_gcm::{
1917
//! aead::{Aead, AeadCore, KeyInit, OsRng},
20-
//! Aes256Gcm, Nonce // Or `Aes128Gcm`
18+
//! Aes256Gcm, Nonce, Key // Or `Aes128Gcm`
2119
//! };
2220
//!
23-
//! let key = Aes256Gcm::generate_key(&mut OsRng);
21+
//! # fn gen_key() -> Result<(), core::array::TryFromSliceError> {
22+
//! // The encryption key can be generated randomly:
23+
//! # #[cfg(all(feature = "getrandom", feature = "std"))] {
24+
//! let key = Aes256Gcm::generate_key(OsRng);
25+
//! # }
26+
//!
27+
//! // Transformed from a byte array:
28+
//! let key: &[u8; 32] = &[42; 32];
29+
//! let key: &Key<Aes256Gcm> = key.into();
30+
//!
31+
//! // Note that you can get byte array from slice using the `TryInto` trait:
32+
//! let key: &[u8] = &[42; 32];
33+
//! let key: [u8; 32] = key.try_into()?;
34+
//! # Ok(()) }
35+
//!
36+
//! # fn main() -> Result<(), aes_gcm::Error> {
37+
//! // Alternatively, the key can be transformed directly from a byte slice
38+
//! // (panicks on lenght mismatch):
39+
//! # let key: &[u8] = &[42; 32];
40+
//! let key = Key::<Aes256Gcm>::from_slice(key);
41+
//!
2442
//! let cipher = Aes256Gcm::new(&key);
2543
//! let nonce = Aes256Gcm::generate_nonce(&mut OsRng); // 96-bits; unique per message
2644
//! let ciphertext = cipher.encrypt(&nonce, b"plaintext message".as_ref())?;

0 commit comments

Comments
 (0)