1use std::fmt;
8use std::path::Path;
9
10use heika_cert::key::{PRIVATE_KEY_DER_LENGTH, private_key_from_der, private_key_from_pem};
11use heika_core::key::PrivateKey;
12use zeroize::Zeroizing;
13
14#[derive(Debug)]
16pub struct KeyFileError(String);
17
18impl fmt::Display for KeyFileError {
19 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20 f.write_str(&self.0)
21 }
22}
23
24impl std::error::Error for KeyFileError {}
25
26pub fn read_private_key(path: &Path) -> Result<PrivateKey, KeyFileError> {
28 let bytes = Zeroizing::new(std::fs::read(path).map_err(|error| {
29 KeyFileError(format!(
30 "鍵のファイル {} を読めません: {error}",
31 path.display()
32 ))
33 })?);
34 parse_private_key(&bytes)
35 .map_err(|what| KeyFileError(format!("鍵のファイル {} は{what}", path.display())))
36}
37
38pub fn others_can_read(path: &Path) -> std::io::Result<bool> {
41 #[cfg(unix)]
42 {
43 use std::os::unix::fs::PermissionsExt;
44 Ok(std::fs::metadata(path)?.permissions().mode() & 0o044 != 0)
45 }
46 #[cfg(not(unix))]
47 {
48 let _ = path;
49 Ok(false)
50 }
51}
52
53fn parse_private_key(bytes: &[u8]) -> Result<PrivateKey, &'static str> {
55 if bytes.len() == PRIVATE_KEY_DER_LENGTH && bytes.first() == Some(&0x30) {
56 return private_key_from_der(bytes).map_err(|_| " DER として読めません");
57 }
58 let text = std::str::from_utf8(bytes).map_err(|_| "、PEM、DER、16 進のどれでもありません")?;
59 let text = text.trim();
60 if text.starts_with("-----BEGIN") {
61 return private_key_from_pem(text).map_err(|_| " PEM として読めません");
62 }
63 if text.len() == 64 {
64 return text.parse().map_err(|_| " 16 進として読めません");
65 }
66 Err("、PEM、DER、16 進のどれでもありません")
67}
68
69#[cfg(test)]
70mod tests {
71 use heika_cert::key::{private_key_to_der, private_key_to_pem};
72 use heika_core::key::PublicKey;
73
74 use super::*;
75
76 #[test]
77 fn reads_pem_der_and_hex_alike() {
78 let key = PrivateKey::from_bytes(&[7; 32]);
79 let public = PublicKey::from_private_key(&key);
80 let pem = private_key_to_pem(&key);
81 let der = private_key_to_der(&key);
82 let hex = format!("{}\n", key.to_hex().as_str());
83 for bytes in [pem.as_bytes(), &der[..], hex.as_bytes()] {
84 let read = parse_private_key(bytes).unwrap();
85 assert_eq!(PublicKey::from_private_key(&read), public);
86 }
87 assert!(parse_private_key(b"not a key").is_err());
88 assert!(parse_private_key(&[0xFF; 48]).is_err());
89 }
90
91 #[cfg(unix)]
92 #[test]
93 fn tells_whether_others_can_read() {
94 use std::os::unix::fs::PermissionsExt;
95 let path = std::env::temp_dir().join(format!("heika-node-key-{}", std::process::id()));
96 std::fs::write(&path, b"").unwrap();
97 for (mode, expected) in [(0o600, false), (0o640, true), (0o604, true), (0o400, false)] {
98 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
99 assert_eq!(others_can_read(&path).unwrap(), expected, "{mode:o}");
100 }
101 std::fs::remove_file(&path).unwrap();
102 }
103}