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    EcdsaSignatureDigestRfc4754 = 18,
99}
100
101#[repr(u32)]
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
103/// Mirrors encryption cases from `SecKeyAlgorithm`.
104pub enum EncryptionAlgorithm {
105    /// Mirrors `kSecKeyAlgorithmRSAEncryptionRaw`: textbook RSA without padding. It is
106    /// deterministic and malleable, so never use it to encrypt data; it only exists for
107    /// implementing other padding schemes. Prefer an OAEP variant.
108    RsaEncryptionRaw = 0,
109    /// Mirrors `kSecKeyAlgorithmRSAEncryptionPKCS1`: PKCS#1 v1.5 padding, which is open to
110    /// padding-oracle (Bleichenbacher) attacks whenever decryption failures are observable.
111    /// Use it only for interoperability; prefer an OAEP variant.
112    RsaEncryptionPkcs1 = 1,
113    /// Mirrors a `SecKeyAlgorithm` encryption constant.
114    RsaEncryptionOaepSha1 = 2,
115    /// Mirrors a `SecKeyAlgorithm` encryption constant.
116    RsaEncryptionOaepSha224 = 3,
117    /// Mirrors a `SecKeyAlgorithm` encryption constant.
118    RsaEncryptionOaepSha256 = 4,
119    /// Mirrors a `SecKeyAlgorithm` encryption constant.
120    RsaEncryptionOaepSha384 = 5,
121    /// Mirrors a `SecKeyAlgorithm` encryption constant.
122    RsaEncryptionOaepSha512 = 6,
123    /// Mirrors a `SecKeyAlgorithm` encryption constant.
124    RsaEncryptionOaepSha1AesGcm = 7,
125    /// Mirrors a `SecKeyAlgorithm` encryption constant.
126    RsaEncryptionOaepSha224AesGcm = 8,
127    /// Mirrors a `SecKeyAlgorithm` encryption constant.
128    RsaEncryptionOaepSha256AesGcm = 9,
129    /// Mirrors a `SecKeyAlgorithm` encryption constant.
130    RsaEncryptionOaepSha384AesGcm = 10,
131    /// Mirrors a `SecKeyAlgorithm` encryption constant.
132    RsaEncryptionOaepSha512AesGcm = 11,
133}
134
135pub(crate) fn key_type_id() -> usize {
136    unsafe { bridge::security_key_get_type_id() }
137}
138
139pub(crate) fn key_block_size(handle: &Handle) -> usize {
140    usize::try_from(unsafe { bridge::security_key_get_block_size(handle.as_ptr()) })
141        .unwrap_or_default()
142}
143
144pub(crate) fn key_external_representation(handle: &Handle) -> Result<Vec<u8>> {
145    let mut status = 0;
146    let mut error = std::ptr::null_mut();
147    let raw = unsafe {
148        bridge::security_key_copy_external_representation(
149            handle.as_ptr(),
150            &raw mut status,
151            &raw mut error,
152        )
153    };
154    bridge::required_data(
155        "security_key_copy_external_representation",
156        raw,
157        status,
158        error,
159    )
160}
161
162pub(crate) fn encrypt_with_public_key(
163    handle: &Handle,
164    algorithm: EncryptionAlgorithm,
165    plaintext: &[u8],
166) -> Result<Vec<u8>> {
167    let mut status = 0;
168    let mut error = std::ptr::null_mut();
169    let raw = unsafe {
170        bridge::security_public_key_create_encrypted_data(
171            handle.as_ptr(),
172            algorithm as u32,
173            plaintext.as_ptr().cast(),
174            bridge::len_to_isize(plaintext.len())?,
175            &raw mut status,
176            &raw mut error,
177        )
178    };
179    bridge::required_data(
180        "security_public_key_create_encrypted_data",
181        raw,
182        status,
183        error,
184    )
185}
186
187pub(crate) fn decrypt_with_private_key(
188    handle: &Handle,
189    algorithm: EncryptionAlgorithm,
190    ciphertext: &[u8],
191) -> Result<Vec<u8>> {
192    let mut status = 0;
193    let mut error = std::ptr::null_mut();
194    let raw = unsafe {
195        bridge::security_private_key_create_decrypted_data(
196            handle.as_ptr(),
197            algorithm as u32,
198            ciphertext.as_ptr().cast(),
199            bridge::len_to_isize(ciphertext.len())?,
200            &raw mut status,
201            &raw mut error,
202        )
203    };
204    bridge::required_data(
205        "security_private_key_create_decrypted_data",
206        raw,
207        status,
208        error,
209    )
210}
211
212#[derive(Debug)]
213/// Wraps a private `SecKeyRef`.
214pub struct PrivateKey {
215    handle: Handle,
216}
217
218impl PrivateKey {
219    /// Wraps the corresponding private `SecKeyRef` operation.
220    pub fn type_id() -> usize {
221        key_type_id()
222    }
223
224    pub(crate) fn from_handle(handle: Handle) -> Self {
225        Self { handle }
226    }
227
228    #[cfg(feature = "full")]
229    pub(crate) fn handle(&self) -> &Handle {
230        &self.handle
231    }
232
233    /// Wraps the corresponding private `SecKeyRef` operation.
234    pub fn from_data(data: &[u8], key_type: KeyType, key_size_bits: usize) -> Result<Self> {
235        let mut status = 0;
236        let mut error = std::ptr::null_mut();
237        let raw = unsafe {
238            bridge::security_private_key_create_with_data(
239                data.as_ptr().cast(),
240                bridge::len_to_isize(data.len())?,
241                key_type as u32,
242                bridge::len_to_isize(key_size_bits)?,
243                &raw mut status,
244                &raw mut error,
245            )
246        };
247        bridge::required_handle("security_private_key_create_with_data", raw, status, error)
248            .map(Self::from_handle)
249    }
250
251    /// Wraps the corresponding private `SecKeyRef` operation.
252    pub fn import_item(
253        data: &[u8],
254        file_name_or_extension: Option<&str>,
255        format: ExternalFormat,
256        item_type: ExternalItemType,
257    ) -> Result<Self> {
258        let file_name_or_extension = file_name_or_extension.map(bridge::cstring).transpose()?;
259        let mut status = 0;
260        let mut error = std::ptr::null_mut();
261        let raw = unsafe {
262            bridge::security_private_key_import_item(
263                data.as_ptr().cast(),
264                bridge::len_to_isize(data.len())?,
265                file_name_or_extension
266                    .as_ref()
267                    .map_or(std::ptr::null(), |value| value.as_ptr()),
268                format as u32,
269                item_type as u32,
270                &raw mut status,
271                &raw mut error,
272            )
273        };
274        bridge::required_handle("security_private_key_import_item", raw, status, error)
275            .map(Self::from_handle)
276    }
277
278    /// Wraps the corresponding private `SecKeyRef` operation.
279    pub fn import_pem(pem: &[u8]) -> Result<Self> {
280        Self::import_item(
281            pem,
282            Some(".pem"),
283            ExternalFormat::Unknown,
284            ExternalItemType::PrivateKey,
285        )
286    }
287
288    /// Wraps the corresponding private `SecKeyRef` operation.
289    pub fn public_key(&self) -> Result<PublicKey> {
290        let mut status = 0;
291        let mut error = std::ptr::null_mut();
292        let raw = unsafe {
293            bridge::security_key_copy_public_key(
294                self.handle.as_ptr(),
295                &raw mut status,
296                &raw mut error,
297            )
298        };
299        bridge::required_handle("security_key_copy_public_key", raw, status, error)
300            .map(PublicKey::from_handle)
301    }
302
303    /// Wraps the corresponding private `SecKeyRef` operation.
304    pub fn attributes(&self) -> Result<Value> {
305        let mut status = 0;
306        let mut error = std::ptr::null_mut();
307        let raw = unsafe {
308            bridge::security_key_copy_attributes(
309                self.handle.as_ptr(),
310                &raw mut status,
311                &raw mut error,
312            )
313        };
314        bridge::required_json("security_key_copy_attributes", raw, status, error)
315    }
316
317    /// Wraps the corresponding private `SecKeyRef` operation.
318    pub fn block_size(&self) -> usize {
319        key_block_size(&self.handle)
320    }
321
322    /// Wraps the corresponding private `SecKeyRef` operation.
323    pub fn external_representation(&self) -> Result<Vec<u8>> {
324        key_external_representation(&self.handle)
325    }
326
327    /// Wraps the corresponding private `SecKeyRef` operation.
328    pub fn sign(&self, algorithm: SignatureAlgorithm, data: &[u8]) -> Result<Vec<u8>> {
329        let mut status = 0;
330        let mut error = std::ptr::null_mut();
331        let raw = unsafe {
332            bridge::security_private_key_create_signature(
333                self.handle.as_ptr(),
334                algorithm as u32,
335                data.as_ptr().cast(),
336                bridge::len_to_isize(data.len())?,
337                &raw mut status,
338                &raw mut error,
339            )
340        };
341        bridge::required_data("security_private_key_create_signature", raw, status, error)
342    }
343
344    /// Wraps the corresponding private `SecKeyRef` operation.
345    pub fn decrypt(&self, algorithm: EncryptionAlgorithm, ciphertext: &[u8]) -> Result<Vec<u8>> {
346        decrypt_with_private_key(&self.handle, algorithm, ciphertext)
347    }
348}