Skip to content

Commit

Permalink
docs: Document the Olm message key struct
Browse files Browse the repository at this point in the history
  • Loading branch information
poljar committed Sep 20, 2024
1 parent 4733fbb commit 970a044
Showing 1 changed file with 25 additions and 6 deletions.
31 changes: 25 additions & 6 deletions src/olm/session/message_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ use crate::{
olm::messages::Message,
};

/// A single-use encryption key for per-message encryption.
///
/// This key is used to encrypt a single message in an Olm session.
pub struct MessageKey {
key: Box<[u8; 32]>,
ratchet_key: RatchetPublicKey,
Expand Down Expand Up @@ -56,38 +59,54 @@ impl Drop for RemoteMessageKey {
}

impl MessageKey {
/// Creates a new [`MessageKey`] from the provided raw 32 bytes, along with
/// a public ratchet key and index.
///
/// The ratchet key and index will be included in the created [`Message`],
/// allowing the message recipient to derive the same [`MessageKey`].
pub const fn new(key: Box<[u8; 32]>, ratchet_key: RatchetPublicKey, index: u64) -> Self {
Self { key, ratchet_key, index }
}

pub fn encrypt_truncated_mac(self, plaintext: &[u8]) -> Message {
/// Encrypt the given plaintext using this [`MessageKey`].
///
/// This method will authenticate the ciphertext using a 32-byte message
/// authentication code (MAC). If you need the message authentication code
/// to be truncated, please take a look at the
/// [`MessageKey::encrypt_truncated_mac()`] method instead.
pub fn encrypt(self, plaintext: &[u8]) -> Message {
let cipher = Cipher::new(&self.key);

let ciphertext = cipher.encrypt(plaintext);

let mut message =
Message::new_truncated_mac(*self.ratchet_key.as_ref(), self.index, ciphertext);
let mut message = Message::new(*self.ratchet_key.as_ref(), self.index, ciphertext);

let mac = cipher.mac(&message.to_mac_bytes());
message.set_mac(mac);

message
}

pub fn encrypt(self, plaintext: &[u8]) -> Message {
/// Encrypts the provided plaintext using this [`MessageKey`].
///
/// This method authenticates the ciphertext with an 8-byte message
/// authentication code (MAC). If you require the full, non-truncated
/// MAC, refer to the [`MessageKey::encrypt()`] method.
pub fn encrypt_truncated_mac(self, plaintext: &[u8]) -> Message {
let cipher = Cipher::new(&self.key);

let ciphertext = cipher.encrypt(plaintext);

let mut message = Message::new(*self.ratchet_key.as_ref(), self.index, ciphertext);
let mut message =
Message::new_truncated_mac(*self.ratchet_key.as_ref(), self.index, ciphertext);

let mac = cipher.mac(&message.to_mac_bytes());
message.set_mac(mac);

message
}

/// Get a reference to the message key's key.
/// Get a reference to the message key's raw 32-bytes.
#[cfg(feature = "low-level-api")]
pub fn key(&self) -> &[u8; 32] {
self.key.as_ref()
Expand Down

0 comments on commit 970a044

Please sign in to comment.