Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

crypto_box: Add optional serde support #27

Merged
merged 5 commits into from
Jan 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/crypto_box.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,4 @@ jobs:
override: true
- run: cargo test --release --features std
- run: cargo test --release --features std,heapless
- run: cargo test --release --features std,serde
86 changes: 86 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions crypto_box/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,26 @@ x25519-dalek = { version = "1", default-features = false }
xsalsa20poly1305 = { version = "0.8", default-features = false, features = ["rand_core"] }
zeroize = { version = ">=1, <1.5", default-features = false }

[dependencies.serde_crate]
package = "serde"
optional = true
version = "1"
default-features = false

[dev-dependencies]
bincode = "1"
rand = "0.8"
rmp-serde = "0.15"

[features]
default = ["alloc", "u64_backend"]
serde = ["serde_crate"]
std = ["rand_core/std", "xsalsa20poly1305/std"]
alloc = ["xsalsa20poly1305/alloc"]
heapless = ["xsalsa20poly1305/heapless"]
u32_backend = ["x25519-dalek/u32_backend"]
u64_backend = ["x25519-dalek/u64_backend"]

[package.metadata.docs.rs]
features = ["serde"]
rustdoc-args = ["--cfg", "docsrs"]
112 changes: 110 additions & 2 deletions crypto_box/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,12 @@ use xsalsa20poly1305::aead::{
use xsalsa20poly1305::XSalsa20Poly1305;
use zeroize::{Zeroize, Zeroizing};

#[cfg(feature = "serde")]
use serde_crate::{
de::{Deserialize, Deserializer},
ser::{Serialize, Serializer},
};

/// Size of a `crypto_box` public or secret key in bytes.
pub const KEY_SIZE: usize = 32;

Expand All @@ -215,7 +221,7 @@ pub const KEY_SIZE: usize = 32;
/// Implemented as an alias for [`GenericArray`].
pub type Tag = GenericArray<u8, U16>;

/// `crypto_box` secret key
/// A `crypto_box` secret key.
#[derive(Clone)]
pub struct SecretKey([u8; KEY_SIZE]);

Expand Down Expand Up @@ -265,7 +271,9 @@ impl Drop for SecretKey {
}
}

/// `crypto_box` public key
/// A `crypto_box` public key.
///
/// This type can be serialized if the `serde` feature is enabled.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct PublicKey([u8; KEY_SIZE]);

Expand Down Expand Up @@ -294,6 +302,68 @@ impl From<[u8; KEY_SIZE]> for PublicKey {
}
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl Serialize for PublicKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_bytes(&self.0)
}
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'de> Deserialize<'de> for PublicKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
use core::convert::TryInto;
use serde_crate::de::{Error, SeqAccess, Visitor};

struct PublicKeyVisitor;

impl<'de> Visitor<'de> for PublicKeyVisitor {
type Value = PublicKey;

fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a 32-byte public key")
}

fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
where
S: SeqAccess<'de>,
{
let mut key_bytes = [0; KEY_SIZE];
for i in 0..KEY_SIZE {
key_bytes[i] = match seq.next_element()? {
Some(val) => val,
None => {
return Err(Error::invalid_length(i - 1, &self));
}
}
}
Ok(PublicKey::from(key_bytes))
}

fn visit_bytes<E>(self, bytes: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
// Convert to array (with length check)
let array: [u8; KEY_SIZE] = bytes
.try_into()
.map_err(|_| Error::invalid_length(bytes.len(), &self))?;
Ok(PublicKey::from(array))
}
}

deserializer.deserialize_bytes(PublicKeyVisitor)
}
}

macro_rules! impl_aead_in_place {
($box:ty, $nonce_size:ty, $tag_size:ty, $ct_overhead:ty) => {
impl AeadCore for $box {
Expand Down Expand Up @@ -415,3 +485,41 @@ impl ChaChaBox {
}

impl_aead_in_place!(ChaChaBox, U24, U16, U0);

#[cfg(test)]
mod tests {
#[test]
#[cfg(feature = "serde")]
fn test_public_key_serialization() {
use super::PublicKey;
use rand_core::RngCore;

// Random PK bytes
let mut public_key_bytes = [0; 32];
let mut rng = rand::thread_rng();
rng.fill_bytes(&mut public_key_bytes);

// Create public key
let public_key = PublicKey::from(public_key_bytes);

// Round-trip serialize with bincode
let serialized =
bincode::serialize(&public_key).expect("Public key could not be serialized");
let deserialized: PublicKey =
bincode::deserialize(&serialized).expect("Public key could not be deserialized");
assert_eq!(
deserialized, public_key,
"Deserialized public key does not match original"
);

// Round-trip serialize with rmp (msgpack)
let serialized =
rmp_serde::to_vec_named(&public_key).expect("Public key could not be serialized");
let deserialized: PublicKey =
rmp_serde::from_slice(&serialized).expect("Public key could not be deserialized");
assert_eq!(
deserialized, public_key,
"Deserialized public key does not match original"
);
}
}