Skip to content

Commit e3f0528

Browse files
committed
Fix serializer
1 parent 2138453 commit e3f0528

File tree

1 file changed

+39
-3
lines changed

1 file changed

+39
-3
lines changed

src/lib/high_level/keys.rs

+39-3
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33
44
use crate::high_level::contexts::EncryptionContext;
55
use crate::high_level::utils::make_rekey_factor;
6-
use crate::internal::arithmetic::{GroupElement, ScalarNonZero, G};
6+
use crate::internal::arithmetic::{GroupElement, ScalarNonZero, ScalarTraits, G};
77
use derive_more::{Deref, From};
88
use rand_core::{CryptoRng, RngCore};
9-
use serde::{Deserialize, Serialize};
9+
use serde::de::{Error, Visitor};
10+
use serde::{Deserialize, Deserializer, Serialize, Serializer};
11+
use std::fmt::Formatter;
1012

1113
/// A global public key associated with the [`GlobalSecretKey`] from which session keys are derived.
1214
/// Can also be used to encrypt messages against, if no session key is available or using a session
@@ -21,9 +23,43 @@ pub struct GlobalSecretKey(pub(crate) ScalarNonZero);
2123
#[derive(Copy, Clone, Eq, PartialEq, Debug, Deref, From, Serialize, Deserialize)]
2224
pub struct SessionPublicKey(pub GroupElement);
2325
/// A session secret key used to decrypt messages with.
24-
#[derive(Copy, Clone, Debug, From, Serialize, Deserialize)]
26+
#[derive(Copy, Clone, Debug, From)]
2527
pub struct SessionSecretKey(pub(crate) ScalarNonZero);
2628

29+
impl Serialize for SessionSecretKey {
30+
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
31+
where
32+
S: Serializer,
33+
{
34+
serializer.serialize_str(self.0.encode_as_hex().as_str())
35+
}
36+
}
37+
impl<'de> Deserialize<'de> for SessionSecretKey {
38+
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
39+
where
40+
D: Deserializer<'de>,
41+
{
42+
struct SessionSecretKeyVisitor;
43+
impl Visitor<'_> for SessionSecretKeyVisitor {
44+
type Value = SessionSecretKey;
45+
fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
46+
formatter.write_str("a hex encoded string representing a SessionSecretKey")
47+
}
48+
49+
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
50+
where
51+
E: Error,
52+
{
53+
ScalarNonZero::decode_from_hex(v)
54+
.map(SessionSecretKey)
55+
.ok_or(E::custom(format!("invalid hex encoded string: {}", v)))
56+
}
57+
}
58+
59+
deserializer.deserialize_str(SessionSecretKeyVisitor)
60+
}
61+
}
62+
2763
/// A trait for public keys, which can be encoded and decoded from byte arrays and hex strings.
2864
pub trait PublicKey {
2965
fn value(&self) -> &GroupElement;

0 commit comments

Comments
 (0)