crypto_generic/
lib.rs

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
8use std::fmt::Debug;
9use std::fmt::Display;
10use std::fmt::Formatter;
11
12use serde::Deserialize;
13use serde::Serialize;
14use zeroize::Zeroize;
15
16mod always_panic_impl;
17use always_panic_impl as crypto_impl;
18pub 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)]
26pub 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)]
34pub struct SecureByteVec {
35    data: Vec<u8>,
36}
37
38impl Display for SecureByteVec {
39    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
40        f.write_str("SecureByteVec")
41    }
42}
43impl Debug for SecureByteVec {
44    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
45        f.write_str("debug: SecureByteVec")
46    }
47}
48
49impl From<Vec<u8>> for SecureByteVec {
50    fn from(value: Vec<u8>) -> Self {
51        Self { data: value }
52    }
53}
54
55impl From<&[u8]> for SecureByteVec {
56    fn from(value: &[u8]) -> Self {
57        value.to_vec().into()
58    }
59}
60
61impl SecureByteVec {
62    pub fn as_slice(&self) -> &[u8] {
63        self.data.as_slice()
64    }
65    pub fn as_mut_slice(&mut self) -> &mut [u8] {
66        self.data.as_mut_slice()
67    }
68}
69
70impl Drop for SecureByteVec {
71    fn drop(&mut self) {
72        self.data.zeroize();
73    }
74}