Skip to content

Commit

Permalink
AAD: fix serialization and deserialization logic
Browse files Browse the repository at this point in the history
In previous commits we did a duplicated base64 encoding and decoding
when serializing/deserializing the AAD field.

Signed-off-by: Xynnn007 <xynnn@linux.alibaba.com>
  • Loading branch information
Xynnn007 committed Dec 12, 2024
1 parent a704036 commit d6151a8
Showing 1 changed file with 12 additions and 14 deletions.
26 changes: 12 additions & 14 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ where
Ok(decoded)
}

fn serialize_base64_option<S>(
fn serialize_base64_vec<S>(
sub: &Option<Vec<u8>>,
serializer: S,
) -> core::result::Result<S::Ok, S::Error>
Expand All @@ -166,25 +166,23 @@ where
{
match sub {
Some(value) => {
let encoded = BASE64_URL_SAFE_NO_PAD.encode(value);
let encoded = String::from_utf8(value.clone()).map_err(serde::ser::Error::custom)?;
serializer.serialize_str(&encoded)
}
None => serializer.serialize_none(),
}
}

fn deserialize_base64_option<'de, D>(
fn deserialize_base64_vec<'de, D>(
deserializer: D,
) -> core::result::Result<Option<Vec<u8>>, D::Error>
where
D: serde::Deserializer<'de>,
{
let encoded = String::deserialize(deserializer)?;
let decoded = BASE64_URL_SAFE_NO_PAD
.decode(encoded)
.map_err(serde::de::Error::custom)?;
let string = String::deserialize(deserializer)?;
let bytes = string.into_bytes();

Ok(Some(decoded))
Ok(Some(bytes))
}

#[derive(Clone, Serialize, Deserialize, Debug)]
Expand All @@ -202,10 +200,10 @@ pub struct Response {
pub encrypted_key: Vec<u8>,

#[serde(
deserialize_with = "deserialize_base64_option",
skip_serializing_if = "Option::is_none",
serialize_with = "serialize_base64_option",
default = "Option::default"
default = "Option::default",
serialize_with = "serialize_base64_vec",
deserialize_with = "deserialize_base64_vec"
)]
pub aad: Option<Vec<u8>>,

Expand Down Expand Up @@ -320,7 +318,7 @@ mod tests {
"protected": "eyJhbGciOiJmYWtlYWxnIiwiZW5jIjoiZmFrZWVuYyJ9Cg",
"encrypted_key": "ZmFrZWtleQ",
"iv": "cmFuZG9tZGF0YQ",
"aad": "ZmFrZWFhZA",
"aad": "fakeaad",
"ciphertext": "ZmFrZWVuY291dHB1dA",
"tag": "ZmFrZXRhZw"
}"#;
Expand All @@ -344,7 +342,7 @@ mod tests {
"protected": "eyJhbGciOiJmYWtlYWxnIiwiZW5jIjoiZmFrZWVuYyIsImZha2VmaWVsZCI6ImZha2V2YWx1ZSJ9",
"encrypted_key": "ZmFrZWtleQ",
"iv": "cmFuZG9tZGF0YQ",
"aad": "ZmFrZWFhZA",
"aad": "fakeaad",
"ciphertext": "ZmFrZWVuY291dHB1dA",
"tag": "ZmFrZXRhZw"
}"#;
Expand Down Expand Up @@ -382,7 +380,7 @@ mod tests {
"protected": "eyJhbGciOiJmYWtlYWxnIiwiZW5jIjoiZmFrZWVuYyIsImZha2VmaWVsZCI6ImZha2V2YWx1ZSJ9",
"encrypted_key": "ZmFrZWtleQ",
"iv": "cmFuZG9tZGF0YQ",
"aad": "ZmFrZWFhZA",
"aad": "fakeaad",
"ciphertext": "ZmFrZWVuY291dHB1dA",
"tag": "ZmFrZXRhZw"
});
Expand Down

0 comments on commit d6151a8

Please sign in to comment.