Skip to main content

crypto_service_sdk/
secret.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2//! Key material and secret text: zeroised on drop, redacted in `Debug`.
3
4use std::fmt;
5
6use serde::{Deserialize, Deserializer, Serialize, Serializer};
7use zeroize::{Zeroize, Zeroizing};
8
9use crate::encoding::{decode_hex, encode_hex, Text};
10
11/// Secret bytes the API carries as hex: private and secret keys, shared
12/// secrets, derived and unwrapped keys, data keys, symmetric keys sent to
13/// the server.
14///
15/// The buffer is overwritten with zeros when the value is dropped, and
16/// `Debug` prints `SecretBytes(<redacted>)`. There is no `Display` and no
17/// `PartialEq`: read the bytes with [`SecretBytes::expose_secret`].
18#[derive(Clone, Default)]
19pub struct SecretBytes(Zeroizing<Vec<u8>>);
20
21/// Secret text: passwords, plaintexts and the decrypted text the server
22/// returns.
23///
24/// The buffer is overwritten with zeros when the value is dropped, and
25/// `Debug` prints `SecretString(<redacted>)`. There is no `Display` and
26/// no `PartialEq`: read the text with [`SecretString::expose_secret`].
27#[derive(Clone, Default)]
28pub struct SecretString(Zeroizing<String>);
29
30impl SecretBytes {
31    /// Wraps `bytes`, which are zeroised when this value is dropped.
32    pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
33        Self(Zeroizing::new(bytes.into()))
34    }
35
36    /// Reads hex text, either case.
37    ///
38    /// # Errors
39    ///
40    /// [`EncodingError`](crate::EncodingError) for text that is not hex.
41    pub fn from_hex(text: &str) -> Result<Self, crate::EncodingError> {
42        decode_hex(text).map(Self::new)
43    }
44
45    /// The secret bytes.
46    #[must_use]
47    pub fn expose_secret(&self) -> &[u8] {
48        &self.0
49    }
50}
51
52impl SecretString {
53    /// Wraps `text`, which is zeroised when this value is dropped.
54    pub fn new(text: impl Into<String>) -> Self {
55        Self(Zeroizing::new(text.into()))
56    }
57
58    /// The secret text.
59    #[must_use]
60    pub fn expose_secret(&self) -> &str {
61        &self.0
62    }
63}
64
65impl From<Vec<u8>> for SecretBytes {
66    fn from(bytes: Vec<u8>) -> Self {
67        Self::new(bytes)
68    }
69}
70
71impl From<&[u8]> for SecretBytes {
72    fn from(bytes: &[u8]) -> Self {
73        Self::new(bytes.to_vec())
74    }
75}
76
77impl<const N: usize> From<[u8; N]> for SecretBytes {
78    fn from(mut bytes: [u8; N]) -> Self {
79        let secret = Self::new(bytes.to_vec());
80        bytes.zeroize();
81        secret
82    }
83}
84
85impl From<String> for SecretString {
86    fn from(text: String) -> Self {
87        Self::new(text)
88    }
89}
90
91impl From<&str> for SecretString {
92    fn from(text: &str) -> Self {
93        Self::new(text)
94    }
95}
96
97impl fmt::Debug for SecretBytes {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        f.write_str("SecretBytes(<redacted>)")
100    }
101}
102
103impl fmt::Debug for SecretString {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        f.write_str("SecretString(<redacted>)")
106    }
107}
108
109impl Serialize for SecretBytes {
110    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
111        let text = Zeroizing::new(encode_hex(&self.0));
112        serializer.serialize_str(&text)
113    }
114}
115
116impl<'de> Deserialize<'de> for SecretBytes {
117    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
118        deserializer.deserialize_str(Text(|text: &str| Self::from_hex(text)))
119    }
120}
121
122impl Serialize for SecretString {
123    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
124        serializer.serialize_str(&self.0)
125    }
126}
127
128impl<'de> Deserialize<'de> for SecretString {
129    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
130        String::deserialize(deserializer).map(Self::new)
131    }
132}
133
134#[cfg(test)]
135mod tests;