use std::path::Path;
use crate::CryptoError;
use crate::key::private::{
PRIVATE_KEY_FILE_READ_CAP_BYTES, PRIVATE_KEY_HEADER_FIXED_SIZE, PrivateKeyHeader,
};
pub const PUBLIC_KEY_FILENAME: &str = "public.key";
pub const PRIVATE_KEY_FILENAME: &str = "private.key";
pub(crate) fn read_private_key_bytes(
path: &Path,
wrapped_secret_cap: u32,
) -> Result<Vec<u8>, CryptoError> {
crate::fs::paths::read_file_staged(
path,
PRIVATE_KEY_HEADER_FIXED_SIZE,
PRIVATE_KEY_FILE_READ_CAP_BYTES,
|head| match PrivateKeyHeader::from_file_bytes(head) {
Ok(header) => usize::try_from(header.declared_len_after_fixed_header(
header.wrapped_secret_len.min(wrapped_secret_cap),
))
.unwrap_or(usize::MAX),
Err(_) => 0,
},
)
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
#[test]
fn a_head_that_is_not_a_private_key_header_is_read_no_further() {
let tmp = tempfile::NamedTempFile::new().unwrap();
fs::write(tmp.path(), vec![0x41u8; 64 * 1024]).unwrap();
for wrapped_secret_cap in [0, u32::MAX] {
let read = read_private_key_bytes(tmp.path(), wrapped_secret_cap).unwrap();
assert_eq!(read.len(), PRIVATE_KEY_HEADER_FIXED_SIZE + 1);
}
}
}