Skip to content

Commit

Permalink
nostr: add nip44::decrypt_to_bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
yukibtc committed Jan 25, 2024
1 parent 751d6d0 commit 0d8b0a7
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 16 deletions.
18 changes: 15 additions & 3 deletions crates/nostr/src/nips/nip44/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,19 @@ pub fn decrypt<T>(
public_key: &XOnlyPublicKey,
payload: T,
) -> Result<String, Error>
where
T: AsRef<[u8]>,
{
let bytes: Vec<u8> = decrypt_to_bytes(secret_key, public_key, payload)?;
String::from_utf8(bytes.to_vec()).map_err(|_| Error::Utf8Encode)
}

/// Decrypt **without** converting bytes to UTF-8 string
pub fn decrypt_to_bytes<T>(
secret_key: &SecretKey,
public_key: &XOnlyPublicKey,
payload: T,
) -> Result<Vec<u8>, Error>
where
T: AsRef<[u8]>,
{
Expand Down Expand Up @@ -212,12 +225,11 @@ where
let mut buffer: Vec<u8> = ciphertext.to_vec();
cipher.apply_keystream(&mut buffer);

// Convert bytes to string
String::from_utf8(buffer.to_vec()).map_err(|_| Error::Utf8Encode)
Ok(buffer)
}
Version::V2 => {
let conversation_key: ConversationKey = ConversationKey::derive(secret_key, public_key);
v2::decrypt(&conversation_key, &payload)
v2::decrypt_to_bytes(&conversation_key, &payload)
}
}
}
Expand Down
13 changes: 1 addition & 12 deletions crates/nostr/src/nips/nip44/v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,17 +227,6 @@ where
Ok(payload)
}

/// Decrypt with NIP44 (v2)
///
/// **The payload MUST be already decoded from base64**
pub fn decrypt<T>(conversation_key: &ConversationKey, payload: T) -> Result<String, Error>
where
T: AsRef<[u8]>,
{
let bytes: Vec<u8> = decrypt_to_bytes(conversation_key, payload)?;
String::from_utf8(bytes).map_err(|e| Error::V2(ErrorV2::from(e)))
}

/// Decrypt with NIP44 (v2)
///
/// **The payload MUST be already decoded from base64**
Expand Down Expand Up @@ -631,7 +620,7 @@ mod tests {
let note = vector.get("note").unwrap().as_str().unwrap();

let payload: Vec<u8> = general_purpose::STANDARD.decode(ciphertext).unwrap();
let result = decrypt(&conversation_key, &payload);
let result = decrypt_to_bytes(&conversation_key, &payload);
assert!(result.is_err(), "Should not have decrypted: {}", note);

let err = result.unwrap_err();
Expand Down
2 changes: 1 addition & 1 deletion crates/nostr/src/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ pub use crate::message::*;
// NIPs
pub use crate::nips::nip01::{self, *};
#[cfg(feature = "nip04")]
pub use crate::nips::nip04::{self, *};
pub use crate::nips::nip04;
#[cfg(all(feature = "std", feature = "nip05"))]
pub use crate::nips::nip05::{self, *};
#[cfg(feature = "nip06")]
Expand Down

0 comments on commit 0d8b0a7

Please sign in to comment.