serdect-0.2.0/.cargo_vcs_info.json0000644000000001450000000000100124640ustar { "git": { "sha1": "e633f5f6d26940ebb0ab6d05209d47378b8a1f4e" }, "path_in_vcs": "serdect" }serdect-0.2.0/CHANGELOG.md000064400000000000000000000012441046102023000130660ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## 0.2.0 (2023-02-26) ### Changed - MSRV 1.60 ([#802]) - Lint improvements ([#824]) - Bump `base16ct` dependency to v0.2 ([#890]) ### Fixed - TOML test ([#864]) [#802]: https://github.com/RustCrypto/formats/pull/802 [#824]: https://github.com/RustCrypto/formats/pull/824 [#864]: https://github.com/RustCrypto/formats/pull/864 [#890]: https://github.com/RustCrypto/formats/pull/890 ## 0.1.0 (2022-03-29) - Initial release serdect-0.2.0/Cargo.toml0000644000000034770000000000100104750ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.60" name = "serdect" version = "0.2.0" authors = ["RustCrypto Developers"] description = """ Constant-time serde serializer/deserializer helpers for data that potentially contains secrets (e.g. cryptographic keys) """ readme = "README.md" keywords = [ "crypto", "constant-time", "serde", ] categories = [ "cryptography", "encoding", "no-std", "parsing", ] license = "Apache-2.0 OR MIT" repository = "https://github.com/RustCrypto/formats/tree/master/serdect" [package.metadata.docs.rs] all-features = true rustdoc-args = [ "--cfg", "docsrs", ] targets = [] [dependencies.base16ct] version = "0.2" default-features = false [dependencies.serde] version = "1.0.96" default-features = false [dependencies.zeroize] version = "1" optional = true default-features = false [dev-dependencies.bincode] version = "1" [dev-dependencies.ciborium] version = "0.2" [dev-dependencies.hex-literal] version = "0.3" [dev-dependencies.proptest] version = "1" [dev-dependencies.serde] version = "1.0.119" features = ["derive"] default-features = false [dev-dependencies.serde-json-core] version = "0.5" features = ["std"] default-features = false [dev-dependencies.serde_json] version = "1" [dev-dependencies.toml] version = "0.7" [features] alloc = [ "base16ct/alloc", "serde/alloc", ] default = ["alloc"] serdect-0.2.0/Cargo.toml.orig000064400000000000000000000022511046102023000141430ustar 00000000000000[package] name = "serdect" description = """ Constant-time serde serializer/deserializer helpers for data that potentially contains secrets (e.g. cryptographic keys) """ version = "0.2.0" authors = ["RustCrypto Developers"] license = "Apache-2.0 OR MIT" repository = "https://github.com/RustCrypto/formats/tree/master/serdect" categories = ["cryptography", "encoding", "no-std", "parsing"] keywords = ["crypto", "constant-time", "serde"] readme = "README.md" edition = "2021" rust-version = "1.60" [dependencies] base16ct = { version = "0.2", default-features = false, path = "../base16ct" } serde = { version = "1.0.96", default-features = false } # optional features zeroize = { version = "1", optional = true, default-features = false } [dev-dependencies] bincode = "1" ciborium = "0.2" hex-literal = "0.3" proptest = "1" serde = { version = "1.0.119", default-features = false, features = ["derive"] } serde_json = "1" serde-json-core = { version = "0.5", default-features = false, features = ["std"] } toml = "0.7" [features] default = ["alloc"] alloc = ["base16ct/alloc", "serde/alloc"] [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "docsrs"] targets = [] serdect-0.2.0/LICENSE-APACHE000064400000000000000000000261361046102023000132100ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. serdect-0.2.0/LICENSE-MIT000064400000000000000000000021021046102023000127030ustar 00000000000000MIT License Copyright (c) 2022 The RustCrypto Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. serdect-0.2.0/README.md000064400000000000000000000050611046102023000125350ustar 00000000000000# [RustCrypto]: Constant-Time Serde Helpers [![Crate][crate-image]][crate-link] [![Docs][docs-image]][docs-link] [![Build Status][build-image]][build-link] ![Apache 2.0/MIT Licensed][license-image] ![MSRV][msrv-image] Constant-time serde serializer/deserializer helpers for data that potentially contains secrets (e.g. cryptographic keys) [Documentation][docs-link] ## About [Serialization is a potential sidechannel for leaking sensitive secrets][Util::Lookup] such as cryptographic keys. This crate provides "best effort" constant-time helper methods for reducing the amount of timing variability involved in serializing/deserializing data when using `serde`, Rust's standard serialization framework. These helper methods conditionally serialize data as hexadecimal using the constant-time [`base16ct`] crate when using human-readable formats such as JSON or TOML. When using a binary format, the data is serialized as-is into binary. While this crate can't ensure that format implementations don't perform other kinds of data-dependent branching on the contents of the serialized data, using a constant-time hex serialization with human-readable formats should help reduce the overall timing variability. ## Minimum Supported Rust Version Rust **1.60** or newer. In the future, we reserve the right to change MSRV (i.e. MSRV is out-of-scope for this crate's SemVer guarantees), however when we do it will be accompanied by a minor version bump. ## License Licensed under either of: * [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) * [MIT license](http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. [//]: # (badges) [crate-image]: https://buildstats.info/crate/serdect [crate-link]: https://crates.io/crates/serdect [docs-image]: https://docs.rs/serdect/badge.svg [docs-link]: https://docs.rs/serdect/ [license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg [msrv-image]: https://img.shields.io/badge/rustc-1.60+-blue.svg [build-image]: https://github.com/RustCrypto/formats/actions/workflows/serdect.yml/badge.svg [build-link]: https://github.com/RustCrypto/formats/actions/workflows/serdect.yml [//]: # (general links) [RustCrypto]: https://github.com/RustCrypto [Util::Lookup]: https://arxiv.org/pdf/2108.04600.pdf [`base16ct`]: https://github.com/RustCrypto/formats/tree/master/base16ct serdect-0.2.0/src/array.rs000064400000000000000000000126711046102023000135360ustar 00000000000000//! Serialization primitives for arrays. use core::fmt; use serde::de::{Error, SeqAccess, Visitor}; use serde::ser::SerializeTuple; use serde::{Deserialize, Deserializer, Serialize, Serializer}; #[cfg(feature = "zeroize")] use zeroize::Zeroize; /// Serialize the given type as lower case hex when using human-readable /// formats or binary if the format is binary. pub fn serialize_hex_lower_or_bin(value: &T, serializer: S) -> Result where S: Serializer, T: AsRef<[u8]>, { if serializer.is_human_readable() { crate::serialize_hex::<_, _, false>(value, serializer) } else { let mut seq = serializer.serialize_tuple(value.as_ref().len())?; for byte in value.as_ref() { seq.serialize_element(byte)?; } seq.end() } } /// Serialize the given type as upper case hex when using human-readable /// formats or binary if the format is binary. pub fn serialize_hex_upper_or_bin(value: &T, serializer: S) -> Result where S: Serializer, T: AsRef<[u8]>, { if serializer.is_human_readable() { crate::serialize_hex::<_, _, true>(value, serializer) } else { let mut seq = serializer.serialize_tuple(value.as_ref().len())?; for byte in value.as_ref() { seq.serialize_element(byte)?; } seq.end() } } /// Deserialize from hex when using human-readable formats or binary if the /// format is binary. Fails if the `buffer` isn't the exact same size as the /// resulting array. pub fn deserialize_hex_or_bin<'de, D>(buffer: &mut [u8], deserializer: D) -> Result<(), D::Error> where D: Deserializer<'de>, { if deserializer.is_human_readable() { struct StrVisitor<'b>(&'b mut [u8]); impl<'de> Visitor<'de> for StrVisitor<'_> { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { write!(formatter, "a string of length {}", self.0.len() * 2) } fn visit_str(self, v: &str) -> Result where E: Error, { if v.len() != self.0.len() * 2 { return Err(Error::invalid_length(v.len(), &self)); } base16ct::mixed::decode(v, self.0).map_err(E::custom)?; Ok(()) } } deserializer.deserialize_str(StrVisitor(buffer)) } else { struct ArrayVisitor<'b>(&'b mut [u8]); impl<'de> Visitor<'de> for ArrayVisitor<'_> { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { write!(formatter, "an array of length {}", self.0.len()) } fn visit_seq(self, mut seq: A) -> Result where A: SeqAccess<'de>, { for (index, byte) in self.0.iter_mut().enumerate() { *byte = match seq.next_element()? { Some(byte) => byte, None => return Err(Error::invalid_length(index, &self)), }; } Ok(()) } } deserializer.deserialize_tuple(buffer.len(), ArrayVisitor(buffer)) } } /// [`HexOrBin`] serializer which uses lower case. pub type HexLowerOrBin = HexOrBin; /// [`HexOrBin`] serializer which uses upper case. pub type HexUpperOrBin = HexOrBin; /// Serializer/deserializer newtype which encodes bytes as either binary or hex. /// /// Use hexadecimal with human-readable formats, or raw binary with binary formats. #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct HexOrBin(pub [u8; N]); impl Default for HexOrBin { fn default() -> Self { Self([0; N]) } } impl AsRef<[u8]> for HexOrBin { fn as_ref(&self) -> &[u8] { self.0.as_ref() } } impl From<&[u8; N]> for HexOrBin { fn from(bytes: &[u8; N]) -> Self { Self(*bytes) } } impl From<[u8; N]> for HexOrBin { fn from(bytes: [u8; N]) -> Self { Self(bytes) } } impl From> for [u8; N] { fn from(hex_or_bin: HexOrBin) -> Self { hex_or_bin.0 } } impl Serialize for HexOrBin { fn serialize(&self, serializer: S) -> Result where S: Serializer, { if UPPERCASE { serialize_hex_upper_or_bin(self, serializer) } else { serialize_hex_lower_or_bin(self, serializer) } } } impl<'de, const N: usize, const UPPERCASE: bool> Deserialize<'de> for HexOrBin { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { let mut buffer = [0; N]; deserialize_hex_or_bin(&mut buffer, deserializer)?; Ok(Self(buffer)) } } #[cfg(feature = "zeroize")] impl Zeroize for HexOrBin { fn zeroize(&mut self) { self.0.as_mut_slice().zeroize(); } } serdect-0.2.0/src/lib.rs000064400000000000000000000114111046102023000131550ustar 00000000000000#![no_std] #![cfg_attr(docsrs, feature(doc_auto_cfg))] #![doc = include_str!("../README.md")] #![doc( html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg", html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg" )] #![forbid(unsafe_code)] #![warn( clippy::mod_module_files, clippy::unwrap_used, missing_docs, rust_2018_idioms, unused_lifetimes, unused_qualifications )] //! ## Usage //! //! ### Implementing `Deserialize` and `Serialize` for arrays. //! #![cfg_attr(feature = "alloc", doc = " ```")] #![cfg_attr(not(feature = "alloc"), doc = " ```ignore")] //! # use serde::{Deserialize, Deserializer, Serialize, Serializer}; //! # //! # #[derive(Debug, PartialEq)] //! struct SecretData([u8; 32]); //! //! impl<'de> Deserialize<'de> for SecretData { //! fn deserialize(deserializer: D) -> Result //! where //! D: Deserializer<'de>, //! { //! let mut buffer = [0; 32]; //! serdect::array::deserialize_hex_or_bin(&mut buffer, deserializer)?; //! Ok(Self(buffer)) //! } //! } //! //! impl Serialize for SecretData { //! fn serialize(&self, serializer: S) -> Result //! where //! S: Serializer, //! { //! serdect::array::serialize_hex_lower_or_bin(&self.0, serializer) //! } //! } //! //! let data = SecretData([42; 32]); //! //! let serialized = bincode::serialize(&data).unwrap(); //! // bincode, a binary serialization format, is serialized into bytes. //! assert_eq!(serialized.as_slice(), [42; 32]); //! # let deserialized: SecretData = bincode::deserialize(&serialized).unwrap(); //! # assert_eq!(deserialized, data); //! //! let serialized = serde_json::to_string(&data).unwrap(); //! // JSON, a human-readable serialization format, is serialized into lower-case HEX. //! assert_eq!( //! serialized, //! "\"2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a\"" //! ); //! # let deserialized: SecretData = serde_json::from_str(&serialized).unwrap(); //! # assert_eq!(deserialized, data); //! ``` //! //! ### Implementing `Deserialize` and `Serialize` for slices. //! #![cfg_attr(feature = "alloc", doc = " ```")] #![cfg_attr(not(feature = "alloc"), doc = " ```ignore")] //! # use serde::{Deserialize, Deserializer, Serialize, Serializer}; //! # //! # #[derive(Debug, PartialEq)] //! struct SecretData(Vec); //! //! impl<'de> Deserialize<'de> for SecretData { //! fn deserialize(deserializer: D) -> Result //! where //! D: Deserializer<'de>, //! { //! serdect::slice::deserialize_hex_or_bin_vec(deserializer).map(Self) //! } //! } //! //! impl Serialize for SecretData { //! fn serialize(&self, serializer: S) -> Result //! where //! S: Serializer, //! { //! serdect::slice::serialize_hex_lower_or_bin(&self.0, serializer) //! } //! } //! //! let data = SecretData(vec![42; 32]); //! //! let serialized = bincode::serialize(&data).unwrap(); //! // bincode, a binary serialization format is serialized into bytes. //! assert_eq!( //! serialized.as_slice(), //! [ //! // Not fixed-size, so a size will be encoded. //! 32, 0, 0, 0, 0, 0, 0, 0, //! // Actual data. //! 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, //! 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, //! ] //! ); //! # let deserialized: SecretData = bincode::deserialize(&serialized).unwrap(); //! # assert_eq!(deserialized, data); //! //! let serialized = serde_json::to_string(&data).unwrap(); //! // JSON, a human-readable serialization format is serialized into lower-case HEX. //! assert_eq!( //! serialized, //! "\"2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a\"" //! ); //! # let deserialized: SecretData = serde_json::from_str(&serialized).unwrap(); //! # assert_eq!(deserialized, data); //! ``` #[cfg(feature = "alloc")] extern crate alloc; pub mod array; pub mod slice; pub use serde; use serde::Serializer; #[cfg(not(feature = "alloc"))] use serde::ser::Error; #[cfg(feature = "alloc")] use serde::Serialize; fn serialize_hex(value: &T, serializer: S) -> Result where S: Serializer, T: AsRef<[u8]>, { #[cfg(feature = "alloc")] if UPPERCASE { return base16ct::upper::encode_string(value.as_ref()).serialize(serializer); } else { return base16ct::lower::encode_string(value.as_ref()).serialize(serializer); } #[cfg(not(feature = "alloc"))] { let _ = value; let _ = serializer; return Err(S::Error::custom( "serializer is human readable, which requires the `alloc` crate feature", )); } } serdect-0.2.0/src/slice.rs000064400000000000000000000155011046102023000135120ustar 00000000000000//! Serialization primitives for slices. use core::fmt; use serde::de::{Error, Visitor}; use serde::{Deserializer, Serialize, Serializer}; #[cfg(feature = "alloc")] use ::{alloc::vec::Vec, serde::Deserialize}; #[cfg(feature = "zeroize")] use zeroize::Zeroize; /// Serialize the given type as lower case hex when using human-readable /// formats or binary if the format is binary. pub fn serialize_hex_lower_or_bin(value: &T, serializer: S) -> Result where S: Serializer, T: AsRef<[u8]>, { if serializer.is_human_readable() { crate::serialize_hex::<_, _, false>(value, serializer) } else { value.as_ref().serialize(serializer) } } /// Serialize the given type as upper case hex when using human-readable /// formats or binary if the format is binary. pub fn serialize_hex_upper_or_bin(value: &T, serializer: S) -> Result where S: Serializer, T: AsRef<[u8]>, { if serializer.is_human_readable() { crate::serialize_hex::<_, _, true>(value, serializer) } else { value.as_ref().serialize(serializer) } } /// Deserialize from hex when using human-readable formats or binary if the /// format is binary. Fails if the `buffer` is smaller then the resulting /// slice. pub fn deserialize_hex_or_bin<'de, D>(buffer: &mut [u8], deserializer: D) -> Result<&[u8], D::Error> where D: Deserializer<'de>, { if deserializer.is_human_readable() { struct StrVisitor<'b>(&'b mut [u8]); impl<'de, 'b> Visitor<'de> for StrVisitor<'b> { type Value = &'b [u8]; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { write!( formatter, "a string with a maximum length of {}", self.0.len() * 2 ) } fn visit_str(self, v: &str) -> Result where E: Error, { // TODO: Map `base16ct::Error::InvalidLength` to `Error::invalid_length`. base16ct::mixed::decode(v, self.0).map_err(E::custom) } } deserializer.deserialize_str(StrVisitor(buffer)) } else { struct SliceVisitor<'b>(&'b mut [u8]); impl<'de, 'b> Visitor<'de> for SliceVisitor<'b> { type Value = &'b [u8]; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { write!( formatter, "a slice with a maximum length of {}", self.0.len() ) } fn visit_bytes(self, v: &[u8]) -> Result where E: Error, { // Workaround for // https://github.com/rust-lang/rfcs/blob/b1de05846d9bc5591d753f611ab8ee84a01fa500/text/2094-nll.md#problem-case-3-conditional-control-flow-across-functions if v.len() <= self.0.len() { let buffer = &mut self.0[..v.len()]; buffer.copy_from_slice(v); return Ok(buffer); } Err(E::invalid_length(v.len(), &self)) } #[cfg(feature = "alloc")] fn visit_byte_buf(self, mut v: Vec) -> Result where E: Error, { // Workaround for // https://github.com/rust-lang/rfcs/blob/b1de05846d9bc5591d753f611ab8ee84a01fa500/text/2094-nll.md#problem-case-3-conditional-control-flow-across-functions if v.len() <= self.0.len() { let buffer = &mut self.0[..v.len()]; buffer.swap_with_slice(&mut v); return Ok(buffer); } Err(E::invalid_length(v.len(), &self)) } } deserializer.deserialize_byte_buf(SliceVisitor(buffer)) } } /// Deserialize from hex when using human-readable formats or binary if the /// format is binary. #[cfg(feature = "alloc")] pub fn deserialize_hex_or_bin_vec<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, { if deserializer.is_human_readable() { struct StrVisitor; impl<'de> Visitor<'de> for StrVisitor { type Value = Vec; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { write!(formatter, "a string") } fn visit_str(self, v: &str) -> Result where E: Error, { base16ct::mixed::decode_vec(v).map_err(E::custom) } } deserializer.deserialize_str(StrVisitor) } else { Vec::deserialize(deserializer) } } /// [`HexOrBin`] serializer which uses lower case. #[cfg(feature = "alloc")] pub type HexLowerOrBin = HexOrBin; /// [`HexOrBin`] serializer which uses upper case. #[cfg(feature = "alloc")] pub type HexUpperOrBin = HexOrBin; /// Serializer/deserializer newtype which encodes bytes as either binary or hex. /// /// Use hexadecimal with human-readable formats, or raw binary with binary formats. #[cfg(feature = "alloc")] #[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct HexOrBin(pub Vec); #[cfg(feature = "alloc")] impl AsRef<[u8]> for HexOrBin { fn as_ref(&self) -> &[u8] { self.0.as_ref() } } #[cfg(feature = "alloc")] impl From<&[u8]> for HexOrBin { fn from(bytes: &[u8]) -> HexOrBin { Self(bytes.into()) } } #[cfg(feature = "alloc")] impl From> for HexOrBin { fn from(vec: Vec) -> HexOrBin { Self(vec) } } #[cfg(feature = "alloc")] impl From> for Vec { fn from(vec: HexOrBin) -> Vec { vec.0 } } #[cfg(feature = "alloc")] impl Serialize for HexOrBin { fn serialize(&self, serializer: S) -> Result where S: Serializer, { if UPPERCASE { serialize_hex_upper_or_bin(self, serializer) } else { serialize_hex_lower_or_bin(self, serializer) } } } #[cfg(feature = "alloc")] impl<'de, const UPPERCASE: bool> Deserialize<'de> for HexOrBin { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { deserialize_hex_or_bin_vec(deserializer).map(Self) } } #[cfg(all(feature = "alloc", feature = "zeroize"))] impl Zeroize for HexOrBin { fn zeroize(&mut self) { self.0.as_mut_slice().zeroize(); } } serdect-0.2.0/tests/bincode.rs000064400000000000000000000044151046102023000143730ustar 00000000000000//! bincode-specific tests. #![cfg(feature = "alloc")] use hex_literal::hex; use proptest::{array::*, collection::vec, prelude::*}; use serdect::{array, slice}; /// Example input to be serialized. const EXAMPLE_BYTES: [u8; 16] = hex!("000102030405060708090A0B0C0D0E0F"); /// bincode serialization of [`EXAMPLE_BYTES`] as a slice. const BINCODE_SLICE: [u8; 24] = hex!("1000000000000000000102030405060708090A0B0C0D0E0F"); /// bincode serialization of [`EXAMPLE_BYTES`] as an array. const BINCODE_ARRAY: [u8; 16] = EXAMPLE_BYTES; #[test] fn deserialize_slice() { let deserialized = bincode::deserialize::(&BINCODE_SLICE).unwrap(); assert_eq!(deserialized.0, EXAMPLE_BYTES); } #[test] fn deserialize_slice_owned() { let deserialized = bincode::deserialize_from::<_, slice::HexUpperOrBin>(BINCODE_SLICE.as_ref()).unwrap(); assert_eq!(deserialized.0, EXAMPLE_BYTES); } #[test] fn deserialize_array() { let deserialized = bincode::deserialize::>(&BINCODE_ARRAY).unwrap(); assert_eq!(deserialized.0, EXAMPLE_BYTES); } #[test] fn deserialize_array_owned() { let deserialized = bincode::deserialize_from::<_, array::HexUpperOrBin<16>>(BINCODE_ARRAY.as_ref()).unwrap(); assert_eq!(deserialized.0, EXAMPLE_BYTES); } #[test] fn serialize_slice() { let serialized = bincode::serialize(&slice::HexUpperOrBin::from(EXAMPLE_BYTES.as_ref())).unwrap(); assert_eq!(&serialized, &BINCODE_SLICE); } #[test] fn serialize_array() { let serialized = bincode::serialize(&array::HexUpperOrBin::from(EXAMPLE_BYTES)).unwrap(); assert_eq!(&serialized, &BINCODE_ARRAY); } proptest! { #[test] fn round_trip_slice(bytes in vec(any::(), 0..1024)) { let serialized = bincode::serialize(&slice::HexUpperOrBin::from(bytes.as_ref())).unwrap(); let deserialized = bincode::deserialize::(&serialized).unwrap(); prop_assert_eq!(bytes, deserialized.0); } #[test] fn round_trip_array(bytes in uniform32(0u8..)) { let serialized = bincode::serialize(&array::HexUpperOrBin::from(bytes)).unwrap(); let deserialized = bincode::deserialize::>(&serialized).unwrap(); prop_assert_eq!(bytes, deserialized.0); } } serdect-0.2.0/tests/cbor.rs000064400000000000000000000037611046102023000137200ustar 00000000000000//! CBOR-specific tests. #![cfg(feature = "alloc")] use ciborium::{de, ser}; use hex_literal::hex; use proptest::{array::*, collection::vec, prelude::*}; use serde::Serialize; use serdect::{array, slice}; /// Example input to be serialized. const EXAMPLE_BYTES: [u8; 16] = hex!("000102030405060708090A0B0C0D0E0F"); /// CBOR serialization of [`EXAMPLE_BYTES`] as a slice. const CBOR_SLICE: [u8; 17] = hex!("90000102030405060708090A0B0C0D0E0F"); /// CBOR serialization of [`EXAMPLE_BYTES`] as an array. const CBOR_ARRAY: [u8; 17] = CBOR_SLICE; #[test] fn deserialize_slice() { let deserialized = de::from_reader::(CBOR_SLICE.as_ref()).unwrap(); assert_eq!(deserialized.0, EXAMPLE_BYTES); } #[test] fn deserialize_array() { let deserialized = de::from_reader::, _>(CBOR_SLICE.as_ref()).unwrap(); assert_eq!(deserialized.0, EXAMPLE_BYTES); } fn serialize(value: &T) -> Vec where T: ?Sized + Serialize, { let mut serialized = Vec::new(); ser::into_writer(value, &mut serialized).unwrap(); serialized } #[test] fn serialize_slice() { let serialized = serialize(&slice::HexUpperOrBin::from(EXAMPLE_BYTES.as_ref())); assert_eq!(&serialized, &CBOR_SLICE); } #[test] fn serialize_array() { let serialized = serialize(&array::HexUpperOrBin::from(EXAMPLE_BYTES)); assert_eq!(&serialized, &CBOR_ARRAY); } proptest! { #[test] fn round_trip_slice(bytes in vec(any::(), 0..1024)) { let serialized = serialize(&slice::HexUpperOrBin::from(bytes.as_ref())); let deserialized = de::from_reader::(serialized.as_slice()).unwrap(); prop_assert_eq!(bytes, deserialized.0); } #[test] fn round_trip_array(bytes in uniform32(0u8..)) { let serialized = serialize(&array::HexUpperOrBin::from(bytes)); let deserialized = de::from_reader::, _>(serialized.as_slice()).unwrap(); prop_assert_eq!(bytes, deserialized.0); } } serdect-0.2.0/tests/serde-json-core.rs000064400000000000000000000062471046102023000157740ustar 00000000000000//! JSON-specific tests. #![cfg(feature = "alloc")] use hex_literal::hex; use proptest::{array::*, collection::vec, prelude::*}; use serde::Serialize; use serde_json_core as json; use serdect::{array, slice}; /// Example input to be serialized. const EXAMPLE_BYTES: [u8; 16] = hex!("000102030405060708090A0B0C0D0E0F"); /// Lower-case hex serialization of [`EXAMPLE_BYTES`]. const HEX_LOWER: &str = "\"000102030405060708090a0b0c0d0e0f\""; /// Upper-case hex serialization of [`EXAMPLE_BYTES`]. const HEX_UPPER: &str = "\"000102030405060708090A0B0C0D0E0F\""; fn serialize(value: &T) -> String where T: Serialize + ?Sized, { // Make sure proptest doesn't fail. let mut buffer = [0; 2048]; let size = json::to_slice(value, &mut buffer).unwrap(); std::str::from_utf8(&buffer[..size]).unwrap().to_string() } #[test] fn deserialize_slice() { let deserialized = json::from_str::(HEX_LOWER).unwrap().0; assert_eq!(deserialized.0, EXAMPLE_BYTES); let deserialized = json::from_str::(HEX_UPPER).unwrap().0; assert_eq!(deserialized.0, EXAMPLE_BYTES); } #[test] fn deserialize_array() { let deserialized = json::from_str::>(HEX_LOWER) .unwrap() .0; assert_eq!(deserialized.0, EXAMPLE_BYTES); let deserialized = json::from_str::>(HEX_UPPER) .unwrap() .0; assert_eq!(deserialized.0, EXAMPLE_BYTES); } #[test] fn serialize_slice() { let serialized = serialize(&slice::HexLowerOrBin::from(EXAMPLE_BYTES.as_ref())); assert_eq!(serialized, HEX_LOWER); let serialized = serialize(&slice::HexUpperOrBin::from(EXAMPLE_BYTES.as_ref())); assert_eq!(serialized, HEX_UPPER); } #[test] fn serialize_array() { let serialized = serialize(&array::HexLowerOrBin::from(EXAMPLE_BYTES)); assert_eq!(serialized, HEX_LOWER); let serialized = serialize(&array::HexUpperOrBin::from(EXAMPLE_BYTES)); assert_eq!(serialized, HEX_UPPER); } proptest! { #[test] fn round_trip_slice_lower(bytes in vec(any::(), 0..1024)) { let serialized = serialize(&slice::HexLowerOrBin::from(bytes.as_ref())); let deserialized = json::from_str::(&serialized).unwrap().0; prop_assert_eq!(bytes, deserialized.0); } #[test] fn round_trip_slice_upper(bytes in vec(any::(), 0..1024)) { let serialized = serialize(&slice::HexUpperOrBin::from(bytes.as_ref())); let deserialized = json::from_str::(&serialized).unwrap().0; prop_assert_eq!(bytes, deserialized.0); } #[test] fn round_trip_array_lower(bytes in uniform32(0u8..)) { let serialized = serialize(&array::HexLowerOrBin::from(bytes)); let deserialized = json::from_str::>(&serialized).unwrap().0; prop_assert_eq!(bytes, deserialized.0); } #[test] fn round_trip_array_upper(bytes in uniform32(0u8..)) { let serialized = serialize(&array::HexUpperOrBin::from(bytes)); let deserialized = json::from_str::>(&serialized).unwrap().0; prop_assert_eq!(bytes, deserialized.0); } } serdect-0.2.0/tests/serde_json.rs000064400000000000000000000071751046102023000151310ustar 00000000000000//! JSON-specific tests. #![cfg(feature = "alloc")] use hex_literal::hex; use proptest::{array::*, collection::vec, prelude::*}; use serde_json as json; use serdect::{array, slice}; /// Example input to be serialized. const EXAMPLE_BYTES: [u8; 16] = hex!("000102030405060708090A0B0C0D0E0F"); /// Lower-case hex serialization of [`EXAMPLE_BYTES`]. const HEX_LOWER: &str = "\"000102030405060708090a0b0c0d0e0f\""; /// Upper-case hex serialization of [`EXAMPLE_BYTES`]. const HEX_UPPER: &str = "\"000102030405060708090A0B0C0D0E0F\""; #[test] fn deserialize_slice() { let deserialized = json::from_str::(HEX_LOWER).unwrap(); assert_eq!(deserialized.0, EXAMPLE_BYTES); let deserialized = json::from_str::(HEX_UPPER).unwrap(); assert_eq!(deserialized.0, EXAMPLE_BYTES); } #[test] fn deserialize_slice_owned() { let deserialized = json::from_reader::<_, slice::HexLowerOrBin>(HEX_LOWER.as_bytes()).unwrap(); assert_eq!(deserialized.0, EXAMPLE_BYTES); let deserialized = json::from_reader::<_, slice::HexUpperOrBin>(HEX_UPPER.as_bytes()).unwrap(); assert_eq!(deserialized.0, EXAMPLE_BYTES); } #[test] fn deserialize_array() { let deserialized = json::from_str::>(HEX_LOWER).unwrap(); assert_eq!(deserialized.0, EXAMPLE_BYTES); let deserialized = json::from_str::>(HEX_UPPER).unwrap(); assert_eq!(deserialized.0, EXAMPLE_BYTES); } #[test] fn deserialize_array_owned() { let deserialized = json::from_reader::<_, array::HexLowerOrBin<16>>(HEX_LOWER.as_bytes()).unwrap(); assert_eq!(deserialized.0, EXAMPLE_BYTES); let deserialized = json::from_reader::<_, array::HexUpperOrBin<16>>(HEX_UPPER.as_bytes()).unwrap(); assert_eq!(deserialized.0, EXAMPLE_BYTES); } #[test] fn serialize_slice() { let serialized = json::to_string(&slice::HexLowerOrBin::from(EXAMPLE_BYTES.as_ref())).unwrap(); assert_eq!(serialized, HEX_LOWER); let serialized = json::to_string(&slice::HexUpperOrBin::from(EXAMPLE_BYTES.as_ref())).unwrap(); assert_eq!(serialized, HEX_UPPER); } #[test] fn serialize_array() { let serialized = json::to_string(&array::HexLowerOrBin::from(EXAMPLE_BYTES)).unwrap(); assert_eq!(serialized, HEX_LOWER); let serialized = json::to_string(&array::HexUpperOrBin::from(EXAMPLE_BYTES)).unwrap(); assert_eq!(serialized, HEX_UPPER); } proptest! { #[test] fn round_trip_slice_lower(bytes in vec(any::(), 0..1024)) { let serialized = json::to_string(&slice::HexLowerOrBin::from(bytes.as_ref())).unwrap(); let deserialized = json::from_str::(&serialized).unwrap(); prop_assert_eq!(bytes, deserialized.0); } #[test] fn round_trip_slice_upper(bytes in vec(any::(), 0..1024)) { let serialized = json::to_string(&slice::HexUpperOrBin::from(bytes.as_ref())).unwrap(); let deserialized = json::from_str::(&serialized).unwrap(); prop_assert_eq!(bytes, deserialized.0); } #[test] fn round_trip_array_lower(bytes in uniform32(0u8..)) { let serialized = json::to_string(&array::HexLowerOrBin::from(bytes)).unwrap(); let deserialized = json::from_str::>(&serialized).unwrap(); prop_assert_eq!(bytes, deserialized.0); } #[test] fn round_trip_array_upper(bytes in uniform32(0u8..)) { let serialized = json::to_string(&array::HexUpperOrBin::from(bytes)).unwrap(); let deserialized = json::from_str::>(&serialized).unwrap(); prop_assert_eq!(bytes, deserialized.0); } } serdect-0.2.0/tests/toml.rs000064400000000000000000000075561046102023000137540ustar 00000000000000//! TOML-specific tests. #![cfg(feature = "alloc")] use hex_literal::hex; use proptest::{array::*, collection::vec, prelude::*}; use serde::{Deserialize, Serialize}; use serdect::{array, slice}; /// Example input to be serialized. const EXAMPLE_BYTES: [u8; 16] = hex!("000102030405060708090A0B0C0D0E0F"); /// Lower-case hex serialization of [`EXAMPLE_BYTES`]. const HEX_LOWER: &str = "\"000102030405060708090a0b0c0d0e0f\""; /// Upper-case hex serialization of [`EXAMPLE_BYTES`]. const HEX_UPPER: &str = "\"000102030405060708090A0B0C0D0E0F\""; #[derive(Deserialize, Serialize)] struct SliceTest { lower: slice::HexLowerOrBin, upper: slice::HexUpperOrBin, } #[derive(Deserialize, Serialize)] struct ArrayTest { lower: array::HexLowerOrBin<16>, upper: array::HexUpperOrBin<16>, } #[test] fn deserialize_slice() { let deserialized = toml::from_str::(&format!("lower={}\nupper={}", HEX_LOWER, HEX_UPPER)).unwrap(); assert_eq!(deserialized.lower.0, EXAMPLE_BYTES); assert_eq!(deserialized.upper.0, EXAMPLE_BYTES); } #[test] fn deserialize_array() { let deserialized = toml::from_str::(&format!("lower={}\nupper={}", HEX_LOWER, HEX_UPPER)).unwrap(); assert_eq!(deserialized.lower.0, EXAMPLE_BYTES); assert_eq!(deserialized.upper.0, EXAMPLE_BYTES); } #[test] fn serialize_slice() { let test = SliceTest { lower: slice::HexLowerOrBin::from(EXAMPLE_BYTES.as_ref()), upper: slice::HexUpperOrBin::from(EXAMPLE_BYTES.as_ref()), }; let serialized = toml::to_string(&test).unwrap(); assert_eq!( serialized, format!("lower = {}\nupper = {}\n", HEX_LOWER, HEX_UPPER) ); } #[test] fn serialize_array() { let test = ArrayTest { lower: array::HexLowerOrBin::from(EXAMPLE_BYTES), upper: array::HexUpperOrBin::from(EXAMPLE_BYTES), }; let serialized = toml::to_string(&test).unwrap(); assert_eq!( serialized, format!("lower = {}\nupper = {}\n", HEX_LOWER, HEX_UPPER) ); } proptest! { #[test] fn round_trip_slice_lower(bytes in vec(any::(), 0..1024)) { #[derive(Debug, Deserialize, PartialEq, Serialize)] pub struct Test { test: slice::HexLowerOrBin, } let test = Test { test: slice::HexLowerOrBin::from(bytes.as_ref()) }; let serialized = toml::to_string(&test).unwrap(); let deserialized = toml::from_str::(&serialized).unwrap(); prop_assert_eq!(test, deserialized); } #[test] fn round_trip_slice_upper(bytes in vec(any::(), 0..1024)) { #[derive(Debug, Deserialize, PartialEq, Serialize)] pub struct Test { test: slice::HexUpperOrBin, } let test = Test { test: slice::HexUpperOrBin::from(bytes.as_ref()) }; let serialized = toml::to_string(&test).unwrap(); let deserialized = toml::from_str::(&serialized).unwrap(); prop_assert_eq!(test, deserialized); } #[test] fn round_trip_array_lower(bytes in uniform32(0u8..)) { #[derive(Debug, Deserialize, PartialEq, Serialize)] pub struct Test { test: array::HexLowerOrBin<32>, } let test = Test { test: array::HexLowerOrBin::from(bytes) }; let serialized = toml::to_string(&test).unwrap(); let deserialized = toml::from_str::(&serialized).unwrap(); prop_assert_eq!(test, deserialized); } #[test] fn round_trip_array_upper(bytes in uniform32(0u8..)) { #[derive(Debug, Deserialize, PartialEq, Serialize)] pub struct Test { test: array::HexUpperOrBin<32>, } let test = Test { test: array::HexUpperOrBin::from(bytes) }; let serialized = toml::to_string(&test).unwrap(); let deserialized = toml::from_str::(&serialized).unwrap(); prop_assert_eq!(test, deserialized); } }