Skip to main content

security/
key.rs

1use serde_json::Value;
2
3use crate::bridge::{self, Handle};
4use crate::certificate::PublicKey;
5use crate::error::Result;
6
7#[repr(u32)]
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9/// Mirrors `SecExternalFormat`.
10pub enum ExternalFormat {
11    /// Mirrors a `SecExternalFormat` constant.
12    Unknown = 0,
13    /// Mirrors a `SecExternalFormat` constant.
14    OpenSsl = 1,
15    /// Mirrors a `SecExternalFormat` constant.
16    Ssh = 2,
17    /// Mirrors a `SecExternalFormat` constant.
18    Bsafe = 3,
19    /// Mirrors a `SecExternalFormat` constant.
20    RawKey = 4,
21    /// Mirrors a `SecExternalFormat` constant.
22    WrappedPkcs8 = 5,
23    /// Mirrors a `SecExternalFormat` constant.
24    WrappedOpenSsl = 6,
25    /// Mirrors a `SecExternalFormat` constant.
26    WrappedSsh = 7,
27    /// Mirrors a `SecExternalFormat` constant.
28    WrappedLsh = 8,
29    /// Mirrors a `SecExternalFormat` constant.
30    X509Certificate = 9,
31    /// Mirrors a `SecExternalFormat` constant.
32    PemSequence = 10,
33    /// Mirrors a `SecExternalFormat` constant.
34    Pkcs7 = 11,
35    /// Mirrors a `SecExternalFormat` constant.
36    Pkcs12 = 12,
37    /// Mirrors a `SecExternalFormat` constant.
38    NetscapeCertificateSequence = 13,
39    /// Mirrors a `SecExternalFormat` constant.
40    SshV2 = 14,
41}
42
43#[repr(u32)]
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
45/// Mirrors `SecExternalItemType`.
46pub enum ExternalItemType {
47    /// Mirrors a `SecExternalItemType` constant.
48    Unknown = 0,
49    /// Mirrors a `SecExternalItemType` constant.
50    PrivateKey = 1,
51    /// Mirrors a `SecExternalItemType` constant.
52    PublicKey = 2,
53    /// Mirrors a `SecExternalItemType` constant.
54    SessionKey = 3,
55    /// Mirrors a `SecExternalItemType` constant.
56    Certificate = 4,
57    /// Mirrors a `SecExternalItemType` constant.
58    Aggregate = 5,
59}
60
61#[repr(u32)]
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63/// Mirrors key-type selectors used with `SecKeyCreateWithData`.
64pub enum KeyType {
65    /// Mirrors a Security.framework key-type selector.
66    Rsa = 0,
67    /// Mirrors a Security.framework key-type selector.
68    EcSecPrimeRandom = 1,
69}
70
71#[repr(u32)]
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73/// Mirrors signing cases from `SecKeyAlgorithm`.
74pub enum SignatureAlgorithm {
75    /// Mirrors a `SecKeyAlgorithm` signing constant.
76    RsaSignatureMessagePkcs1v15Sha256 = 0,
77    /// Mirrors a `SecKeyAlgorithm` signing constant.
78    RsaSignatureDigestPkcs1v15Sha256 = 1,
79    /// Mirrors a `SecKeyAlgorithm` signing constant.
80    RsaSignatureMessagePssSha256 = 2,
81    /// Mirrors a `SecKeyAlgorithm` signing constant.
82    EcdsaSignatureMessageX962Sha256 = 3,
83    /// Mirrors a `SecKeyAlgorithm` signing constant.
84    EcdsaSignatureDigestX962Sha256 = 4,
85    RsaSignatureMessagePkcs1v15Sha384 = 5,
86    RsaSignatureMessagePkcs1v15Sha512 = 6,
87    RsaSignatureDigestPkcs1v15Sha384 = 7,
88    RsaSignatureDigestPkcs1v15Sha512 = 8,
89    RsaSignatureMessagePssSha384 = 9,
90    RsaSignatureMessagePssSha512 = 10,
91    RsaSignatureDigestPssSha256 = 11,
92    RsaSignatureDigestPssSha384 = 12,
93    RsaSignatureDigestPssSha512 = 13,
94    EcdsaSignatureMessageX962Sha384 = 14,
95    EcdsaSignatureMessageX962Sha512 = 15,
96    EcdsaSignatureDigestX962Sha384 = 16,
97    EcdsaSignatureDigestX962Sha512 = 17,
98}
99
100#[repr(u32)]
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
102/// Mirrors encryption cases from `SecKeyAlgorithm`.
103pub enum EncryptionAlgorithm {
104    /// Mirrors `kSecKeyAlgorithmRSAEncryptionRaw`: textbook RSA without padding. It is
105    /// deterministic and malleable, so never use it to encrypt data; it only exists for
106    /// implementing other padding schemes. Prefer an OAEP variant.
107    RsaEncryptionRaw = 0,
108    /// Mirrors `kSecKeyAlgorithmRSAEncryptionPKCS1`: PKCS#1 v1.5 padding, which is open to
109    /// padding-oracle (Bleichenbacher) attacks whenever decryption failures are observable.
110    /// Use it only for interoperability; prefer an OAEP variant.
111    RsaEncryptionPkcs1 = 1,
112    /// Mirrors a `SecKeyAlgorithm` encryption constant.
113    RsaEncryptionOaepSha1 = 2,
114    /// Mirrors a `SecKeyAlgorithm` encryption constant.
115    RsaEncryptionOaepSha224 = 3,
116    /// Mirrors a `SecKeyAlgorithm` encryption constant.
117    RsaEncryptionOaepSha256 = 4,
118    /// Mirrors a `SecKeyAlgorithm` encryption constant.
119    RsaEncryptionOaepSha384 = 5,
120    /// Mirrors a `SecKeyAlgorithm` encryption constant.
121    RsaEncryptionOaepSha512 = 6,
122    /// Mirrors a `SecKeyAlgorithm` encryption constant.
123    RsaEncryptionOaepSha1AesGcm = 7,
124    /// Mirrors a `SecKeyAlgorithm` encryption constant.
125    RsaEncryptionOaepSha224AesGcm = 8,
126    /// Mirrors a `SecKeyAlgorithm` encryption constant.
127    RsaEncryptionOaepSha256AesGcm = 9,
128    /// Mirrors a `SecKeyAlgorithm` encryption constant.
129    RsaEncryptionOaepSha384AesGcm = 10,
130    /// Mirrors a `SecKeyAlgorithm` encryption constant.
131    RsaEncryptionOaepSha512AesGcm = 11,
132}
133
134pub(crate) fn key_type_id() -> usize {
135    unsafe { bridge::security_key_get_type_id() }
136}
137
138pub(crate) fn key_block_size(handle: &Handle) -> usize {
139    usize::try_from(unsafe { bridge::security_key_get_block_size(handle.as_ptr()) })
140        .unwrap_or_default()
141}
142
143pub(crate) fn key_external_representation(handle: &Handle) -> Result<Vec<u8>> {
144    let mut status = 0;
145    let mut error = std::ptr::null_mut();
146    let raw = unsafe {
147        bridge::security_key_copy_external_representation(
148            handle.as_ptr(),
149            &raw mut status,
150            &raw mut error,
151        )
152    };
153    bridge::required_data(
154        "security_key_copy_external_representation",
155        raw,
156        status,
157        error,
158    )
159}
160
161pub(crate) fn encrypt_with_public_key(
162    handle: &Handle,
163    algorithm: EncryptionAlgorithm,
164    plaintext: &[u8],
165) -> Result<Vec<u8>> {
166    let mut status = 0;
167    let mut error = std::ptr::null_mut();
168    let raw = unsafe {
169        bridge::security_public_key_create_encrypted_data(
170            handle.as_ptr(),
171            algorithm as u32,
172            plaintext.as_ptr().cast(),
173            bridge::len_to_isize(plaintext.len())?,
174            &raw mut status,
175            &raw mut error,
176        )
177    };
178    bridge::required_data(
179        "security_public_key_create_encrypted_data",
180        raw,
181        status,
182        error,
183    )
184}
185
186pub(crate) fn decrypt_with_private_key(
187    handle: &Handle,
188    algorithm: EncryptionAlgorithm,
189    ciphertext: &[u8],
190) -> Result<Vec<u8>> {
191    let mut status = 0;
192    let mut error = std::ptr::null_mut();
193    let raw = unsafe {
194        bridge::security_private_key_create_decrypted_data(
195            handle.as_ptr(),
196            algorithm as u32,
197            ciphertext.as_ptr().cast(),
198            bridge::len_to_isize(ciphertext.len())?,
199            &raw mut status,
200            &raw mut error,
201        )
202    };
203    bridge::required_data(
204        "security_private_key_create_decrypted_data",
205        raw,
206        status,
207        error,
208    )
209}
210
211#[derive(Debug)]
212/// Wraps a private `SecKeyRef`.
213pub struct PrivateKey {
214    handle: Handle,
215}
216
217impl PrivateKey {
218    /// Wraps the corresponding private `SecKeyRef` operation.
219    pub fn type_id() -> usize {
220        key_type_id()
221    }
222
223    pub(crate) fn from_handle(handle: Handle) -> Self {
224        Self { handle }
225    }
226
227    pub(crate) fn handle(&self) -> &Handle {
228        &self.handle
229    }
230
231    /// Wraps the corresponding private `SecKeyRef` operation.
232    pub fn from_data(data: &[u8], key_type: KeyType, key_size_bits: usize) -> Result<Self> {
233        let mut status = 0;
234        let mut error = std::ptr::null_mut();
235        let raw = unsafe {
236            bridge::security_private_key_create_with_data(
237                data.as_ptr().cast(),
238                bridge::len_to_isize(data.len())?,
239                key_type as u32,
240                bridge::len_to_isize(key_size_bits)?,
241                &raw mut status,
242                &raw mut error,
243            )
244        };
245        bridge::required_handle("security_private_key_create_with_data", raw, status, error)
246            .map(Self::from_handle)
247    }
248
249    /// Wraps the corresponding private `SecKeyRef` operation.
250    pub fn import_item(
251        data: &[u8],
252        file_name_or_extension: Option<&str>,
253        format: ExternalFormat,
254        item_type: ExternalItemType,
255    ) -> Result<Self> {
256        let file_name_or_extension = file_name_or_extension.map(bridge::cstring).transpose()?;
257        let mut status = 0;
258        let mut error = std::ptr::null_mut();
259        let raw = unsafe {
260            bridge::security_private_key_import_item(
261                data.as_ptr().cast(),
262                bridge::len_to_isize(data.len())?,
263                file_name_or_extension
264                    .as_ref()
265                    .map_or(std::ptr::null(), |value| value.as_ptr()),
266                format as u32,
267                item_type as u32,
268                &raw mut status,
269                &raw mut error,
270            )
271        };
272        bridge::required_handle("security_private_key_import_item", raw, status, error)
273            .map(Self::from_handle)
274    }
275
276    /// Wraps the corresponding private `SecKeyRef` operation.
277    pub fn import_pem(pem: &[u8]) -> Result<Self> {
278        Self::import_item(
279            pem,
280            Some(".pem"),
281            ExternalFormat::Unknown,
282            ExternalItemType::PrivateKey,
283        )
284    }
285
286    /// Wraps the corresponding private `SecKeyRef` operation.
287    pub fn public_key(&self) -> Result<PublicKey> {
288        let mut status = 0;
289        let mut error = std::ptr::null_mut();
290        let raw = unsafe {
291            bridge::security_key_copy_public_key(
292                self.handle.as_ptr(),
293                &raw mut status,
294                &raw mut error,
295            )
296        };
297        bridge::required_handle("security_key_copy_public_key", raw, status, error)
298            .map(PublicKey::from_handle)
299    }
300
301    /// Wraps the corresponding private `SecKeyRef` operation.
302    pub fn attributes(&self) -> Result<Value> {
303        let mut status = 0;
304        let mut error = std::ptr::null_mut();
305        let raw = unsafe {
306            bridge::security_key_copy_attributes(
307                self.handle.as_ptr(),
308                &raw mut status,
309                &raw mut error,
310            )
311        };
312        bridge::required_json("security_key_copy_attributes", raw, status, error)
313    }
314
315    /// Wraps the corresponding private `SecKeyRef` operation.
316    pub fn block_size(&self) -> usize {
317        key_block_size(&self.handle)
318    }
319
320    /// Wraps the corresponding private `SecKeyRef` operation.
321    pub fn external_representation(&self) -> Result<Vec<u8>> {
322        key_external_representation(&self.handle)
323    }
324
325    /// Wraps the corresponding private `SecKeyRef` operation.
326    pub fn sign(&self, algorithm: SignatureAlgorithm, data: &[u8]) -> Result<Vec<u8>> {
327        let mut status = 0;
328        let mut error = std::ptr::null_mut();
329        let raw = unsafe {
330            bridge::security_private_key_create_signature(
331                self.handle.as_ptr(),
332                algorithm as u32,
333                data.as_ptr().cast(),
334                bridge::len_to_isize(data.len())?,
335                &raw mut status,
336                &raw mut error,
337            )
338        };
339        bridge::required_data("security_private_key_create_signature", raw, status, error)
340    }
341
342    /// Wraps the corresponding private `SecKeyRef` operation.
343    pub fn decrypt(&self, algorithm: EncryptionAlgorithm, ciphertext: &[u8]) -> Result<Vec<u8>> {
344        decrypt_with_private_key(&self.handle, algorithm, ciphertext)
345    }
346}