xref: /aosp_15_r20/external/crosvm/vendor/generic/crypto/src/lib.rs (revision bb4ee6a4ae7042d18b07a98463b9c8b875e44b39)
1 // Copyright 2024 The ChromiumOS Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 //! Provides simple Read/Write wrappers that transparently encrypt/decrypt data
6 //! that passes through them.
7 
8 use std::fmt::Debug;
9 use std::fmt::Display;
10 use std::fmt::Formatter;
11 
12 use serde::Deserialize;
13 use serde::Serialize;
14 use zeroize::Zeroize;
15 
16 mod always_panic_impl;
17 use always_panic_impl as crypto_impl;
18 pub use crypto_impl::*;
19 
20 /// Stores a cryptographic key, but permits no access to the underlying data outside of this crate.
21 ///
22 /// Note: there may be multiple copies of this trait because we want to restrict the internals
23 /// to access only within this crate.
24 #[derive(Clone, Default, Serialize, Deserialize)]
25 #[repr(transparent)]
26 pub struct CryptKey {
27     pub(crate) key_bytes: SecureByteVec,
28 }
29 
30 /// A vec wrapper suitable for storing cryptographic key material. On drop, the memory used will be
31 /// zeroed.
32 #[derive(Clone, Default, Serialize, Deserialize)]
33 #[repr(transparent)]
34 pub struct SecureByteVec {
35     data: Vec<u8>,
36 }
37 
38 impl Display for SecureByteVec {
fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result39     fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
40         f.write_str("SecureByteVec")
41     }
42 }
43 impl Debug for SecureByteVec {
fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result44     fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
45         f.write_str("debug: SecureByteVec")
46     }
47 }
48 
49 impl From<Vec<u8>> for SecureByteVec {
from(value: Vec<u8>) -> Self50     fn from(value: Vec<u8>) -> Self {
51         Self { data: value }
52     }
53 }
54 
55 impl From<&[u8]> for SecureByteVec {
from(value: &[u8]) -> Self56     fn from(value: &[u8]) -> Self {
57         value.to_vec().into()
58     }
59 }
60 
61 impl SecureByteVec {
as_slice(&self) -> &[u8]62     pub fn as_slice(&self) -> &[u8] {
63         self.data.as_slice()
64     }
as_mut_slice(&mut self) -> &mut [u8]65     pub fn as_mut_slice(&mut self) -> &mut [u8] {
66         self.data.as_mut_slice()
67     }
68 }
69 
70 impl Drop for SecureByteVec {
drop(&mut self)71     fn drop(&mut self) {
72         self.data.zeroize();
73     }
74 }
75