security_framework/os/macos/
digest_transform.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
//! Digest Transform support

use core_foundation::base::{CFIndex, TCFType};
use core_foundation::data::CFData;
use core_foundation::error::CFError;
use core_foundation::string::CFString;
use core_foundation_sys::base::CFTypeRef;
use core_foundation_sys::data::CFDataRef;
use core_foundation_sys::string::CFStringRef;
use security_framework_sys::digest_transform::*;
use security_framework_sys::transform::kSecTransformInputAttributeName;
use std::ptr;

use crate::os::macos::transform::SecTransform;

#[derive(Debug, Copy, Clone)]
/// A type of digest.
pub struct DigestType(CFStringRef);

#[allow(missing_docs)]
impl DigestType {
    #[inline(always)]
    #[must_use]
    pub fn hmac_md5() -> Self {
        unsafe { Self(kSecDigestHMACMD5) }
    }

    #[inline(always)]
    #[must_use]
    pub fn hmac_sha1() -> Self {
        unsafe { Self(kSecDigestHMACSHA1) }
    }

    #[inline(always)]
    #[must_use]
    pub fn hmac_sha2() -> Self {
        unsafe { Self(kSecDigestHMACSHA2) }
    }

    #[inline(always)]
    #[must_use]
    pub fn md2() -> Self {
        unsafe { Self(kSecDigestMD2) }
    }

    #[inline(always)]
    #[must_use]
    pub fn md4() -> Self {
        unsafe { Self(kSecDigestMD4) }
    }

    #[inline(always)]
    #[must_use]
    pub fn md5() -> Self {
        unsafe { Self(kSecDigestMD5) }
    }

    #[inline(always)]
    #[must_use]
    pub fn sha1() -> Self {
        unsafe { Self(kSecDigestSHA1) }
    }

    #[inline(always)]
    #[must_use]
    pub fn sha2() -> Self {
        unsafe { Self(kSecDigestSHA2) }
    }

    #[inline(always)]
    fn to_type(self) -> CFTypeRef {
        self.0 as CFTypeRef
    }
}

/// A builder for digest transform operations.
pub struct Builder {
    digest_type: Option<DigestType>,
    digest_length: Option<CFIndex>,
    hmac_key: Option<CFData>,
}

impl Default for Builder {
    #[inline(always)]
    fn default() -> Self {
        Self::new()
    }
}

impl Builder {
    /// Returns a new builder with default settings.
    #[inline(always)]
    #[must_use]
    pub fn new() -> Self {
        Self {
            digest_type: None,
            digest_length: None,
            hmac_key: None,
        }
    }

    /// Sets the type of digest to perform.
    ///
    /// If not set, an appropriate digest will be selected for you.
    #[inline]
    pub fn type_(&mut self, digest_type: DigestType) -> &mut Self {
        self.digest_type = Some(digest_type);
        self
    }

    /// Sets the output length of the digest.
    ///
    /// If not set, an appropriate length will be selected for you. Some digest
    /// types only support specific output lengths.
    #[inline]
    pub fn length(&mut self, digest_length: CFIndex) -> &mut Self {
        self.digest_length = Some(digest_length);
        self
    }

    /// Sets the key used for HMAC digests.
    ///
    /// Only applies to `HmacMd5`, `HmacSha1`, and `HmacSha2` digests.
    #[inline]
    pub fn hmac_key(&mut self, hmac_key: CFData) -> &mut Self {
        self.hmac_key = Some(hmac_key);
        self
    }

    /// Computes the digest of the data.
    pub fn execute(&self, data: &CFData) -> Result<CFData, CFError> {
        unsafe {
            let digest_type = match self.digest_type {
                Some(ref digest_type) => digest_type.to_type(),
                None => ptr::null(),
            };

            let digest_length = self.digest_length.unwrap_or(0);

            let mut error = ptr::null_mut();
            let transform = SecDigestTransformCreate(digest_type, digest_length, &mut error);
            if transform.is_null() {
                return Err(CFError::wrap_under_create_rule(error));
            }
            let mut transform = SecTransform::wrap_under_create_rule(transform);

            if let Some(ref hmac_key) = self.hmac_key {
                let key = CFString::wrap_under_get_rule(kSecDigestHMACKeyAttribute);
                transform.set_attribute(&key, hmac_key)?;
            }

            let key = CFString::wrap_under_get_rule(kSecTransformInputAttributeName);
            transform.set_attribute(&key, data)?;

            let result = transform.execute()?;
            Ok(CFData::wrap_under_get_rule(
                result.as_CFTypeRef() as CFDataRef
            ))
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn md5() {
        let data = CFData::from_buffer("The quick brown fox jumps over the lazy dog".as_bytes());
        let hash = Builder::new()
            .type_(DigestType::md5())
            .execute(&data)
            .unwrap();
        assert_eq!(
            hex::encode(hash.bytes()),
            "9e107d9d372bb6826bd81d3542a419d6"
        );
    }

    #[test]
    fn hmac_sha1() {
        let data = CFData::from_buffer("The quick brown fox jumps over the lazy dog".as_bytes());
        let key = CFData::from_buffer(b"key");
        let hash = Builder::new()
            .type_(DigestType::hmac_sha1())
            .hmac_key(key)
            .execute(&data)
            .unwrap();
        assert_eq!(
            hex::encode(hash.bytes()),
            "de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9"
        );
    }
}