Skip to main content

optee_utee/
crypto_op.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use alloc::{boxed::Box, vec::Vec};
19use core::{mem, ptr};
20
21use optee_utee_sys as raw;
22
23use crate::{Attribute, GenericObject, Result, TransientObject, tee_check};
24
25/// Specify one of the available cryptographic operations.
26#[repr(u32)]
27pub enum OperationMode {
28    /// Encryption mode
29    Encrypt = 0,
30    /// Decryption mode
31    Decrypt = 1,
32    /// Signature generation mode
33    Sign = 2,
34    /// Signature verfication mode
35    Verify = 3,
36    /// MAC mode
37    Mac = 4,
38    /// Digest mode
39    Digest = 5,
40    /// Key derivation mode
41    Derive = 6,
42    /// Reserve for testing and validation
43    IllegalValue = 0x7fffffff,
44}
45
46/// Represent the information about a crypto information.
47pub struct OperationInfo {
48    raw: raw::TEE_OperationInfo,
49}
50
51impl OperationInfo {
52    /// Return the `OperationInfo` struct based on the raw struct `TEE_OperationInfo`.
53    ///
54    /// The raw structure contains following fields:
55    ///
56    /// 1) `algorithm`: One of the algorithm of [AlgorithmId](AlgorithmId).
57    /// 2) `mode`: One of the mode of [OperationMode](OperationMode).
58    /// 3) `maxKeySize`: The maximum key sizes of different algorithms as defined in
59    ///    [TransientObjectType](../object/enum.TransientObjectType.html).
60    /// 4) `operationClass`: One of the constants from [OperationConstant](OperationConstant).
61    /// 5) `keySize`:
62    ///    5.1) For an operation that makes no use of keys, 0.
63    ///    5.2) For an operation that uses a single key, the actual size of this key.
64    ///    5.3) For an operation that uses multiple keys, 0. (The actual value of `keySize` can be obtained from
65    ///    [OperationInfoMultiple](OperationInfoMultiple)).
66    /// 6) `requiredKeyUsage`:
67    ///    6.1) For an operation that makes no use of keys, 0.
68    ///    6.2) For an operation that uses a single key, a bit vector that describes the necessary bits in the object
69    ///    usage for `set_key` functions to succeed without panicking.
70    ///    6.3) For an operation that uses multiple keys, 0. (The actual value of `requiredKeyUsage` can be obtained from
71    ///    [OperationInfoMultiple](OperationInfoMultiple)).
72    /// 7) `digestLength`: For a [Mac](Mac), [AE](AE), or [Digest](Digest), describes the number of bytes in the digest or tag.
73    /// 8) `handleState`: A bit vector describing the current state of the operation. Contains one or more of the
74    ///    [HandleFlag](../object/struct.HandleFlag.html).
75    pub fn from_raw(raw: raw::TEE_OperationInfo) -> Self {
76        Self { raw }
77    }
78
79    /// Return the `keySize` field of the raw structure `TEE_OperationInfo`.
80    pub fn key_size(&self) -> u32 {
81        self.raw.keySize
82    }
83
84    /// Return the `maxDataSize` field of the raw structure `TEE_OperationInfo`.
85    pub fn max_key_size(&self) -> u32 {
86        self.raw.maxKeySize
87    }
88}
89
90/// Every operation of [AE](AE), [Asymmetric](Asymmetric), [Cipher](Cipher),
91/// [DeriveKey](DeriveKey), [Digest](Digest), [Mac](Mac) can be either one of the two states.
92#[repr(u32)]
93pub enum OperationStates {
94    /// Nothing is going on.
95    Initial = 0x00000000,
96    /// An operation is in progress.
97    Active = 0x00000001,
98}
99
100/// Define the supported crypto operation.
101pub enum OperationConstant {
102    /// [Cipher](Cipher)
103    Cipher = 1,
104    /// [Mac](Mac)
105    Mac = 3,
106    /// [AE](AE)
107    Ae = 4,
108    /// [Digest](Digest)
109    Digest = 5,
110    /// [Asymmetric](Asymmetric)
111    AsymmetricCipher = 6,
112    /// [Asymmetric](Asymmetric)
113    AsymmetricSignature = 7,
114    /// [DeriveKey](DeriveKey)
115    KeyDerivation = 8,
116}
117
118/// Represent the information about a crypto information which uses multiple keys.
119pub struct OperationInfoMultiple {
120    raw: *mut raw::TEE_OperationInfoMultiple,
121    size: usize,
122}
123
124impl OperationInfoMultiple {
125    /// Return the `OperationInfoMultiple` struct based on the raw struct `TEE_OperationInfo`.
126    ///
127    /// The raw structure contains following fields:
128    ///
129    /// 1) `algorithm`: One of the algorithm of [AlgorithmId](AlgorithmId).
130    /// 2) `mode`: One of the mode of [OperationMode](OperationMode).
131    /// 3) `maxKeySize`: The maximum key sizes of different algorithms as defined in
132    ///    [TransientObjectType](../object/enum.TransientObjectType.html).
133    /// 4) `operationClass`: One of the constants from [OperationConstant](OperationConstant).
134    /// 5) `digestLength`: For a [Mac](Mac), [AE](AE), or [Digest](Digest), describes the number of bytes in the digest or tag.
135    /// 6) `handleState`: A bit vector describing the current state of the operation. Contains one or more of the
136    ///    [HandleFlag](../object/struct.HandleFlag.html).
137    /// 7) `operationState`: Every operation has two states which are defined as
138    ///    [OperationStates](OperationStates).
139    /// 8) `numberOfKeys`: This is set to the number of keys required by this operation. May be 0 for an operation which requires no keys.
140    /// 9) `keyInformation`: This array contains numberOfKeys entries, each of which defines the details for one key used by the operation,
141    ///    in the order they are defined.
142    ///    If the buffer is larger than required to support `numberOfKeys` entries, the additional space is not initialized or modified.
143    ///    For each element:
144    ///    9.1) `keySize`: If a key is programmed in the operation, the actual size of this key, otherwise 0.
145    ///    9.2) `requiredKeyUsage`: A bit vector that describes the necessary bits in the object usage for `set_key` or `set_key_2` to succeed without panicking.
146    pub fn from_raw(raw: *mut raw::TEE_OperationInfoMultiple, size: usize) -> Self {
147        Self { raw, size }
148    }
149
150    /// Return the raw struct `TEE_OperationInfoMultiple`.
151    pub fn raw(&self) -> *mut raw::TEE_OperationInfoMultiple {
152        self.raw
153    }
154
155    /// Return the `size` field of the raw structure `TEE_OperationInfoMultiple`.
156    pub fn size(&self) -> usize {
157        self.size
158    }
159}
160
161/// An opaque reference that identifies a particular cryptographic operation.
162pub struct OperationHandle {
163    raw: *mut raw::TEE_OperationHandle,
164}
165
166impl OperationHandle {
167    fn from_raw(raw: *mut raw::TEE_OperationHandle) -> OperationHandle {
168        Self { raw }
169    }
170
171    fn handle(&self) -> raw::TEE_OperationHandle {
172        unsafe { *(self.raw) }
173    }
174
175    fn null() -> Self {
176        OperationHandle::from_raw(ptr::null_mut())
177    }
178
179    fn allocate(algo: AlgorithmId, mode: OperationMode, max_key_size: usize) -> Result<Self> {
180        let raw_handle: *mut raw::TEE_OperationHandle = Box::into_raw(Box::new(ptr::null_mut()));
181        tee_check(unsafe {
182            raw::TEE_AllocateOperation(
183                raw_handle as *mut _,
184                algo as u32,
185                mode as u32,
186                max_key_size as u32,
187            )
188        })?;
189        Ok(Self::from_raw(raw_handle))
190    }
191
192    fn info(&self) -> OperationInfo {
193        let mut raw_info: raw::TEE_OperationInfo = unsafe { mem::zeroed() };
194        unsafe { raw::TEE_GetOperationInfo(self.handle(), &mut raw_info) };
195        OperationInfo::from_raw(raw_info)
196    }
197
198    fn info_multiple(&self, info_buf: &mut [u8]) -> Result<OperationInfoMultiple> {
199        let mut tmp_size: usize = 0;
200        tee_check(unsafe {
201            raw::TEE_GetOperationInfoMultiple(self.handle(), info_buf.as_ptr() as _, &mut tmp_size)
202        })?;
203        Ok(OperationInfoMultiple::from_raw(
204            info_buf.as_ptr() as _,
205            tmp_size,
206        ))
207    }
208
209    fn reset(&mut self) {
210        unsafe {
211            raw::TEE_ResetOperation(self.handle());
212        }
213    }
214
215    fn set_key<T: GenericObject>(&self, object: &T) -> Result<()> {
216        tee_check(unsafe { raw::TEE_SetOperationKey(self.handle(), *object.as_raw_ref()) })
217    }
218
219    fn set_key_2<T: GenericObject, D: GenericObject>(
220        &self,
221        object1: &T,
222        object2: &D,
223    ) -> Result<()> {
224        tee_check(unsafe {
225            raw::TEE_SetOperationKey2(self.handle(), *object1.as_raw_ref(), *object2.as_raw_ref())
226        })
227    }
228
229    fn copy<T: OpHandle>(&mut self, src: &T) {
230        unsafe {
231            raw::TEE_CopyOperation(self.handle(), src.handle());
232        }
233    }
234}
235
236/// determine whether a combination of algId and element is supported
237pub fn is_algorithm_supported(alg_id: u32, element: u32) -> Result<()> {
238    tee_check(unsafe { raw::TEE_IsAlgorithmSupported(alg_id, element) })
239}
240
241// free before check it's not null
242/// Deallocate all resources associated with an operation handle. After this function is called,
243/// the operation handle is no longer valid. All cryptographic material in the operation is destroyed.
244impl Drop for OperationHandle {
245    fn drop(&mut self) {
246        unsafe {
247            if !self.raw.is_null() {
248                raw::TEE_FreeOperation(self.handle());
249            }
250            drop(Box::from_raw(self.raw));
251        }
252    }
253}
254
255/// A trait for a crypto operation to return its handle.
256pub trait OpHandle {
257    // TODO: returning raw value without lifetime constrait is not a good idea
258    // see https://github.com/apache/teaclave-trustzone-sdk/issues/288
259    /// Return the handle of an operation.
260    fn handle(&self) -> raw::TEE_OperationHandle;
261}
262
263/// An operation for digest the message.
264pub struct Digest(OperationHandle);
265
266impl Digest {
267    /// Accumulate message data for hashing. The message does not have to be block aligned.
268    /// Subsequent calls to this function are possible. The operation may be in either
269    /// initial or active state and becomes active.
270    ///
271    /// # Parameters
272    ///
273    /// 1) `chunk`: Chunk of data to be hashed
274    ///
275    /// # Panics
276    ///
277    /// 1) If the operation is not allocated with valid algorithms.
278    /// 2) if input data exceeds maximum length for algorithm.
279    /// 3) Hardware or cryptographic algorithm failure.
280    /// 4) If the Implementation detects any other error.
281    pub fn update(&self, chunk: &[u8]) {
282        unsafe {
283            raw::TEE_DigestUpdate(self.handle(), chunk.as_ptr() as _, chunk.len());
284        }
285    }
286
287    /// Finalize the message digest operation and produces the message hash. Afterwards the
288    /// Message Digest operation is reset to initial state and can be reused.
289    ///
290    /// # Parameters
291    ///
292    /// 1) `chunk`: Last chunk of data to be hashed.
293    /// 2) `hash`: Output buffer filled with the message hash. This buffer should be large enough to
294    ///    hold the hash message. The real used size is returned by this function.
295    ///
296    /// # Example
297    ///
298    /// ``` rust,no_run
299    /// # use optee_utee::{Digest, AlgorithmId};
300    /// # fn main() -> optee_utee::Result<()> {
301    /// let chunk1 = [0u8;8];
302    /// let chunk2 = [1u8;8];
303    /// let mut hash = [0u8;32];
304    /// match Digest::allocate(AlgorithmId::Sha256) {
305    ///     Ok(operation) =>
306    ///     {
307    ///         operation.update(&chunk1);
308    ///         match operation.do_final(&chunk2, &mut hash) {
309    ///             Ok(hash_len) => {
310    ///                 // ...
311    ///                 Ok(())
312    ///             }
313    ///             Err(e) => Err(e),
314    ///         }
315    ///     }
316    ///     Err(e) => Err(e),
317    /// }
318    /// # }
319    /// ```
320    ///
321    /// # Errors
322    ///
323    /// 1) `ShortBuffer`: If the `hash` is too small. Operation is not finalized for this error.
324    ///
325    /// # Panics
326    /// 1) If the operation is not allocated with valid algorithms.
327    /// 2) if input data exceeds maximum length for algorithm.
328    /// 3) Hardware or cryptographic algorithm failure.
329    /// 4) If the Implementation detects any other error.
330    //hash size is dynamic changed so we returned it's updated size
331    pub fn do_final(&self, chunk: &[u8], hash: &mut [u8]) -> Result<usize> {
332        let mut hash_size: usize = hash.len();
333        tee_check(unsafe {
334            raw::TEE_DigestDoFinal(
335                self.handle(),
336                chunk.as_ptr() as _,
337                chunk.len(),
338                hash.as_mut_ptr() as _,
339                &mut hash_size,
340            )
341        })?;
342        Ok(hash_size)
343    }
344
345    /// Create a Digest operation without any specific algorithm or other data.
346    pub fn null() -> Self {
347        Self(OperationHandle::null())
348    }
349
350    /// Allocate a new cryptographic operation and sets the mode and algorithm type.
351    ///
352    /// # Parameters
353    ///
354    /// 1) `algo`: One of the algorithms that support Digest as listed in
355    ///    [AlgorithmId](AlgorithmId).
356    /// 2) `max_key_size`: The maximum key sizes of different algorithms as defined in
357    ///    [TransientObjectType](../object/enum.TransientObjectType.html).
358    ///
359    /// # Example
360    ///
361    /// ``` rust,no_run
362    /// # use optee_utee::{Digest, AlgorithmId};
363    /// # fn main() -> optee_utee::Result<()> {
364    /// match Digest::allocate(AlgorithmId::Sha256) {
365    ///     Ok(operation) =>
366    ///     {
367    ///         // ...
368    ///         Ok(())
369    ///     }
370    ///     Err(e) => Err(e),
371    /// }
372    /// # }
373    /// ```
374    ///
375    /// # Errors
376    ///
377    /// 1) `OutOfMemory`: If not enough resources are available to allocate the object handle.
378    /// 2) `NotSupported`: If the key size is not supported or the object type is not supported.
379    ///
380    /// # Panics
381    ///
382    /// 1) If the Implementation detects any error associated with this function which is not
383    ///    explicitly associated with a defined return code for this function.
384    pub fn allocate(algo: AlgorithmId) -> Result<Self> {
385        match OperationHandle::allocate(algo, OperationMode::Digest, 0) {
386            Ok(handle) => Ok(Self(handle)),
387            Err(e) => Err(e),
388        }
389    }
390
391    /// Return the characteristics of a Digest operation.
392    ///
393    /// # Example
394    ///
395    /// ``` rust,no_run
396    /// # use optee_utee::{Digest, AlgorithmId};
397    /// # fn main() -> optee_utee::Result<()> {
398    /// match Digest::allocate(AlgorithmId::Md5) {
399    ///     Ok(operation) =>
400    ///     {
401    ///         let info = operation.info();
402    ///         Ok(())
403    ///     }
404    ///     Err(e) => Err(e),
405    /// }
406    /// # }
407    /// ```
408    ///
409    /// # Panics
410    /// 1) If the operation is not a valid opened operation.
411    /// 2) if the Implementation detecs any other error.
412    pub fn info(&self) -> OperationInfo {
413        self.0.info()
414    }
415
416    /// Return the characteristics of a Digest operation with multiple keys.
417    ///
418    /// # Parameters
419    ///
420    /// 1) `info_buf`: The buffer is supposed to save multiple keys, and its size should be large enough before passed in.
421    ///    The number of keys about this operation can be calculated as: OperationInfoMultiple::size -
422    ///    size_of([OperationInfoMultiple](OperationInfoMultiple)) / size_of ( raw::TEE_OperationInfoKey)+1.
423    ///
424    /// # Example
425    ///
426    /// ``` rust,no_run
427    /// # use optee_utee::{Digest, AlgorithmId};
428    /// # fn main() -> optee_utee::Result<()> {
429    /// match Digest::allocate(AlgorithmId::Md5) {
430    ///     Ok(operation) =>
431    ///     {
432    ///         let mut buffer = [0u8, 12];
433    ///         match operation.info_multiple(&mut buffer) {
434    ///             Ok(info_multiple) => {
435    ///                 // ...
436    ///                 Ok(())
437    ///             }
438    ///             Err(e) => Err(e),
439    ///         }
440    ///     }
441    ///     Err(e) => Err(e),
442    /// }
443    /// # }
444    /// ```
445    ///
446    /// # Errors:
447    ///
448    /// 1) `ShortBuffer`: If the `info_buf` is not large enough to hold an
449    ///    [OperationInfoMultiple](OperationInfoMultiple) and the corresponding keys.
450    ///
451    /// # Panics:
452    ///
453    /// 1) If operation is not a valid opened object.
454    /// 2) If the Implementation detects any other error.
455    // Here the multiple info total size is not sure
456    // Passed in array is supposed to provide enough size for this struct
457    pub fn info_multiple(&self, info_buf: &mut [u8]) -> Result<OperationInfoMultiple> {
458        self.0.info_multiple(info_buf)
459    }
460
461    /// Reset the operation state to the state after initial [allocate](Digest::allocate) with the
462    /// add addition of any keys which were configured subsequent to this so that current operation
463    /// can be reused with the same keys.
464    ///
465    /// # Panics
466    ///
467    /// 1) If operation is not a valid opened object.
468    /// 2) If the key has not been set yet.
469    /// 3) Hardware or cryptographic algorithm failure.
470    /// 4) If the Implementation detects any other error.
471    pub fn reset(&mut self) {
472        self.0.reset()
473    }
474
475    /// Copy an operation state to another operation. This also copies the key material associated
476    /// with the source operation.
477    ///
478    /// # Parameters
479    ///
480    /// 1) `src`: the source operation.
481    ///    1.1) If `src` has no key programmed, then the key of this operation is cleared. If there is a key
482    ///    programmed in srcOperation, then the maximum key size of current SHALL be greater than or
483    ///    equal to the actual key size of src.
484    ///
485    /// # Example
486    ///
487    /// ``` rust,no_run
488    /// # use optee_utee::{Digest, AlgorithmId};
489    /// # fn main() -> optee_utee::Result<()> {
490    /// match Digest::allocate(AlgorithmId::Sha256) {
491    ///     Ok(mut operation) =>
492    ///     {
493    ///         match Digest::allocate(AlgorithmId::Sha256) {
494    ///             Ok(operation2) =>
495    ///             {
496    ///                 // ...
497    ///                 operation.copy(&operation2);
498    ///                 Ok(())
499    ///             },
500    ///             Err(e) => Err(e),
501    ///         }
502    ///     },
503    ///     Err(e) => Err(e),
504    /// }
505    /// # }
506    /// ```
507    ///
508    /// # Panics
509    ///
510    /// 1) If the operation or source operation is not a valid opened operation.
511    /// 2) If the alogirhtm or mode differe in two perations.
512    /// 3) If `src` has akey and its size is greater than the maximum key size of the operation.
513    /// 4) Hardware or cryptographic algorithm failure.
514    /// 5) If the Implementation detects any other error.
515    pub fn copy<T: OpHandle>(&mut self, src: &T) {
516        self.0.copy(src)
517    }
518}
519
520impl OpHandle for Digest {
521    fn handle(&self) -> raw::TEE_OperationHandle {
522        self.0.handle()
523    }
524}
525
526/// An operation for conducting symmetric cipher encryption / decryption.
527/// This operation defines the way to perform symmetric cipher operations, such as AES.
528/// They cover both block ciphers and stream ciphers.
529pub struct Cipher(OperationHandle);
530
531impl Cipher {
532    /// Start the symmetric cipher operation. The function should be called after the
533    /// [set_key](Cipher::set_key) or [set_key_2](Cipher::set_key_2).
534    ///
535    /// After called, if the operation is in active state, it is reset and then initialized.
536    /// If the operation is in initial state, it is moved to active state.
537    ///
538    /// # Parameters
539    ///
540    /// 1) `iv`: buffer contains the operation Initialization Vector, which is used for:
541    ///    1.1) [AesCbcNopad](AlgorithmId::AesCbcNopad): IV;
542    ///    1.2) [AesCtr](AlgorithmId::AesCtr): Initial Counter Value;
543    ///    1.3) [AesCts](AlgorithmId::AesCts): IV;
544    ///    1.4) [AesXts](AlgorithmId::AesXts): Tweak Value;
545    ///    1.5) [AesCcm](AlgorithmId::AesCcm): Nonce Value;
546    ///    1.6) [AesGcm](AlgorithmId::AesGcm): Nonce Value;
547    ///    1.7) [AesCbcNopad](AlgorithmId::AesCbcNopad): IV.
548    ///
549    /// # Panics
550    ///
551    /// 1) If the algorithm is not a valid algorithm for `Cipher`.
552    /// 2) If no key is programmed in the operation.
553    /// 3) If the IV does not have the length required by the algorithm.
554    /// 4) Hardware or cryptographic algorithm failure.
555    /// 5) If the Implementation detects any other error.
556    pub fn init(&self, iv: &[u8]) {
557        unsafe { raw::TEE_CipherInit(self.handle(), iv.as_ptr() as _, iv.len()) };
558    }
559
560    /// Encrypt or decrypt the source data.
561    ///
562    /// Input data does not have to be a multiple of block size. Subsequent calls to this function are possible.
563    /// Unless one or more calls of this function have supplied sufficient input data, no output is generated.
564    /// The function should be called after the [init](Cipher::init).
565    ///
566    /// # Parameters
567    ///
568    /// 1) `src`: Input data buffer to be encrypted or decrypted.
569    /// 2) `dest`: Output buffer.
570    ///
571    /// # Example
572    ///
573    /// ``` rust,no_run
574    /// # use optee_utee::{Cipher, AlgorithmId, TransientObject, TransientObjectType};
575    /// # use optee_utee::{AttributeMemref, AttributeId, OperationMode};
576    /// # fn main() -> optee_utee::Result<()> {
577    /// let iv = [0u8, 16];
578    /// let key = [0u8, 16];
579    /// let src = [1u8; 4096];
580    /// let mut dest = [0u8; 4096];
581    /// match Cipher::allocate(AlgorithmId::AesCtr, OperationMode::Encrypt, 128) {
582    ///     Ok(operation) =>
583    ///     {
584    ///         match TransientObject::allocate(TransientObjectType::Aes, 128) {
585    ///             Ok(mut object) =>
586    ///             {
587    ///                 let attr = AttributeMemref::from_ref(AttributeId::SecretValue, &key);
588    ///                 object.populate(&[attr.into()])?;
589    ///                 operation.set_key(&object)?;
590    ///                 operation.init(&iv);
591    ///                 operation.update(&src, &mut dest)?;
592    ///                 Ok(())
593    ///             }
594    ///             Err(e) => Err(e),
595    ///         }
596    ///     }
597    ///     Err(e) => Err(e),
598    /// }
599    /// # }
600    /// ```
601    ///
602    /// # Errors
603    ///
604    /// 1) `ShortBuffer`: If the output buffer is not large enough to contain the output.
605    ///    In this case, the input is not fed into the algorithm.
606    ///
607    /// # Panics
608    ///
609    /// 1) If the algorithm is not a valid algorithm for `Cipher`.
610    /// 2) If the function is called before [init](Cipher::init) or after
611    ///    [do_final](Cipher::do_final).
612    /// 3) Hardware or cryptographic algorithm failure.
613    /// 4) If the Implementation detects any other error.
614    pub fn update(&self, src: &[u8], dest: &mut [u8]) -> Result<usize> {
615        let mut dest_size: usize = dest.len();
616        tee_check(unsafe {
617            raw::TEE_CipherUpdate(
618                self.handle(),
619                src.as_ptr() as _,
620                src.len(),
621                dest.as_mut_ptr() as _,
622                &mut dest_size,
623            )
624        })?;
625        Ok(dest_size)
626    }
627
628    /// Finalize the cipher operation, processing data that has not been processed by previous calls
629    /// to [update](Cipher::update) as well as data supplied in `src`. The operation handle can be reused or re-initialized.
630    ///
631    /// # Parameters
632    ///
633    /// 1) `src`: Input data buffer to be encrypted or decrypted.
634    /// 2) `dest`: Output buffer.
635    ///
636    /// # Errors
637    ///
638    /// 1) `ShortBuffer`: If the output buffer is not large enough to contain the output.
639    ///
640    /// # Panics
641    ///
642    /// 1) If the algorithm is not a valid algorithm for `Cipher`.
643    /// 2) If the function is called before [init](Cipher::init).
644    /// 3) Hardware or cryptographic algorithm failure.
645    /// 4) If the Implementation detects any other error.
646    pub fn do_final(&self, src: &[u8], dest: &mut [u8]) -> Result<usize> {
647        let mut dest_size: usize = dest.len();
648        tee_check(unsafe {
649            raw::TEE_CipherDoFinal(
650                self.handle(),
651                src.as_ptr() as _,
652                src.len(),
653                dest.as_mut_ptr() as _,
654                &mut dest_size,
655            )
656        })?;
657        Ok(dest_size)
658    }
659
660    /// Create a Cipher operation without any specific algorithm or other data.
661    pub fn null() -> Self {
662        Self(OperationHandle::null())
663    }
664
665    /// Function usage is similar to [Digest::allocate](Digest::allocate).
666    pub fn allocate(algo: AlgorithmId, mode: OperationMode, max_key_size: usize) -> Result<Self> {
667        match OperationHandle::allocate(algo, mode, max_key_size) {
668            Ok(handle) => Ok(Self(handle)),
669            Err(e) => Err(e),
670        }
671    }
672
673    /// Function usage is similar to [Digest::info](Digest::info).
674    pub fn info(&self) -> OperationInfo {
675        self.0.info()
676    }
677
678    /// Function usage is similar to [Digest::info_multiple](Digest::info_multiple).
679    pub fn info_multiple(&self, info_buf: &mut [u8]) -> Result<OperationInfoMultiple> {
680        self.0.info_multiple(info_buf)
681    }
682
683    /// Program the key of Digest operation. That ids, it associates the operation with a key.
684    ///
685    /// # Parameters
686    ///
687    /// 1) `object`: The object can either be a [Transient](../object/struct.TransientObject.html)
688    ///    or [Persistent](../object/struct.PersistentObject.html). The key material is copied from
689    ///    the key object handle into the operation. After the key has been set, there is no longer
690    ///    any link between the operation and the key object. The object handle can be closed or reset
691    ///    and this will not affect the operation. This copied material exists until the operation is
692    ///    freed or another key is set into the operation.
693    ///
694    /// # Errors
695    ///
696    /// 1) `CorruptObject`: If the object is corrupt. The object handle is closed.
697    /// 2) `StorageNotAvailable`: If the object is stored in a storage area which is
698    ///    currently inaccessible.
699    ///
700    /// # Panics
701    ///
702    /// 1) If operation is not a valid opened object.
703    /// 2) If object is not null and is not a valid key object.
704    /// 3) If object is not initialized.
705    /// 4) If the operation expect two keys as [AesXts](AlgorithmId::AesXts).
706    /// 5) If the type, size, or usage of object is not compatible with the algorithm, mode, or size of the operation.
707    /// 6) If operation is not in initial state.
708    /// 7) Hardware or cryptographic algorithm failure.
709    /// 8) If the Implementation detects any other error.
710    pub fn set_key<T: GenericObject>(&self, object: &T) -> Result<()> {
711        self.0.set_key(object)
712    }
713
714    /// Initialize an expisting operation with two keys for [AesXts](AlgorithmId::AesXts).
715    ///
716    /// # Parameters:
717    ///
718    /// object1 and object2 SHALL both be non-NULL or both NULL. object1 and object2 SHALL NOT refer to keys with
719    /// bitwise identical [SecretValue](../object/enum.AttributeId.html#variant.SecretValue) attributes.
720    ///
721    /// # Errors
722    ///
723    /// 1) `CorruptObject`: If the object1 is corrupt. The object handle is closed.
724    /// 2) `CorruptObject2`: If the object2 is corrupt. The object handle is closed.
725    /// 3) `StorageNotAvailable`: If the object1 is stored in a storage area which is
726    ///    currently inaccessible.
727    /// 4) `StorageNotAvailable2`: If the object2 is stored in a storage area which is
728    ///    currently inaccessible.
729    ///
730    /// # Panics
731    ///
732    /// 1) If operation is not a valid opened object.
733    /// 2) If object1 and object2 are not both null and object1 or object2 or both are not a valid key object.
734    /// 3) If object1 or object2 is not initialized.
735    /// 4) If the operation algorithm is not [AesXts](AlgorithmId::AesXts).
736    /// 5) If the type, size, or usage of any object is not compatible with the algorithm, mode, or size of the operation.
737    /// 6) If operation is not in initial state.
738    /// 7) Hardware or cryptographic algorithm failure.
739    /// 8) If the Implementation detects any other error.
740    pub fn set_key_2<T: GenericObject, D: GenericObject>(
741        &self,
742        object1: &T,
743        object2: &D,
744    ) -> Result<()> {
745        self.0.set_key_2(object1, object2)
746    }
747
748    /// Function usage is similar to [Digest::copy](Digest::copy).
749    pub fn copy<T: OpHandle>(&mut self, src: &T) {
750        self.0.copy(src)
751    }
752}
753
754impl OpHandle for Cipher {
755    fn handle(&self) -> raw::TEE_OperationHandle {
756        self.0.handle()
757    }
758}
759
760/// An operation for performing MAC (Message Authentication Code) operations, such as `HMAC`
761/// or `AES-CMAC` operations. This operation is not used for Authenticated Encryption algorithms,
762/// which SHALL use the functions defined in [AE](AE).
763pub struct Mac(OperationHandle);
764
765impl Mac {
766    /// Initialize a MAC opeartion. The The function should be called after the
767    /// [set_key](Mac::set_key).
768    ///
769    /// # Parameters
770    ///
771    /// 1) `iv`: Input buffer containing the operation Initialization Vector, if applicable
772    ///
773    /// # Panics
774    ///
775    /// 1) If the algorithm is not a valid algorithm for `Mac`.
776    /// 2) If no key is programmed in the operation.
777    /// 3) If the Initialization Vector does not have the length required by the algorithm.
778    /// 4) Hardware or cryptographic algorithm failure.
779    /// 5) If the Implementation detects any other error.
780    pub fn init(&self, iv: &[u8]) {
781        unsafe { raw::TEE_MACInit(self.handle(), iv.as_ptr() as _, iv.len()) };
782    }
783
784    /// Accumulate data for a MAC calculation.
785    ///
786    /// Input data does not have to be a multiple of block size. Subsequent calls to this function are possible.
787    /// Unless one or more calls of this function have supplied sufficient input data, no output is generated.
788    /// The function should be called after the [init](Mac::init).
789    ///
790    /// # Parameters
791    ///
792    /// 1) `chunk`: Chunk of the message to be MACed.
793    ///
794    /// # Panics
795    ///
796    /// 1) If the algorithm is not a valid algorithm for `Mac`.
797    /// 2) If the function is called before [init](Mac::init) or after
798    ///    [compute_final](Mac::compute_final) or after [compare_final](Mac::compare_final).
799    /// 3) If `chunk` excceds maximum length for algorithm.
800    /// 4) Hardware or cryptographic algorithm failure.
801    /// 5) If the Implementation detects any other error.
802    pub fn update(&self, chunk: &[u8]) {
803        unsafe { raw::TEE_MACUpdate(self.handle(), chunk.as_ptr() as _, chunk.len()) };
804    }
805    /// Finalize the MAC operation with a last chunk of message, and computes the MAC.
806    /// Afterwards the operation handle can be reused or re-initialized with a new key.
807    /// The operation SHALL be in active state and moves to initial state afterwards.
808    ///
809    /// # Parameters:
810    ///
811    /// `message`: Input buffer containing a last message chunk to MAC
812    /// `mac`: Output buffer filled with the computed MAC, the size should be allocated enough for
813    /// containing the whole computed MAC
814    ///
815    /// # Example
816    ///
817    /// ``` rust,no_run
818    /// # use optee_utee::{
819    ///     TransientObject,
820    ///     TransientObjectType,
821    ///     Attribute,
822    ///     AttributeMemref,
823    ///     AttributeId,
824    ///     Mac,
825    ///     AlgorithmId,
826    /// };
827    /// # fn main() -> optee_utee::Result<()> {
828    /// let mut key: [u8; 20] = [
829    /// 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35,
830    /// 0x36, 0x37, 0x38, 0x39, 0x30,];
831    /// let mut out: [u8; 20] = [0u8; 20];
832    /// match Mac::allocate(AlgorithmId::HmacSha1, key.len() * 8) {
833    ///     Err(e) => return Err(e),
834    ///     Ok(mac) => {
835    ///         match TransientObject::allocate(TransientObjectType::HmacSha1, key.len() * 8) {
836    ///             Err(e) => return Err(e),
837    ///             Ok(mut key_object) => {
838    ///                 let attr = AttributeMemref::from_ref(AttributeId::SecretValue, &key);
839    ///                 key_object.populate(&[attr.into()])?;
840    ///                 mac.set_key(&key_object)?;
841    ///             }
842    ///         }
843    ///         mac.init(&[0u8; 0]);
844    ///         mac.update(&[0u8; 8]);
845    ///         mac.compute_final(&[0u8; 0], &mut out)?;
846    ///         Ok(())
847    ///     }
848    /// }
849    /// # }
850    /// ```
851    ///
852    /// # Errors
853    ///
854    /// 1) `ShortBuffer`: If the output buffer is not large enough to contain the output.
855    ///
856    /// # Panics
857    ///
858    /// 1) If the algorithm is not a valid algorithm for `Mac`.
859    /// 2) If the function is called before before [init](Mac::init) or after
860    ///    [compute_final](Mac::compute_final) or after [compare_final](Mac::compare_final).
861    /// 3) If input data exceeds maximum length for algorithm.
862    /// 4) Hardware or cryptographic algorithm failure.
863    /// 5) If the Implementation detects any other error.
864    pub fn compute_final(&self, message: &[u8], mac: &mut [u8]) -> Result<usize> {
865        let mut mac_size: usize = mac.len();
866        tee_check(unsafe {
867            raw::TEE_MACComputeFinal(
868                self.handle(),
869                message.as_ptr() as _,
870                message.len(),
871                mac.as_mut_ptr() as _,
872                &mut mac_size,
873            )
874        })?;
875        Ok(mac_size)
876    }
877
878    /// Finalize the MAC operation and compares the MAC with the buffer passed to the function.
879    /// Afterwards the operation handle can be reused or re-initialized with a new key.
880    /// The operation SHALL be in active state and moves to initial state afterwards.
881    ///
882    /// # Parameters:
883    ///
884    /// `message`: Input buffer containing a last message chunk to MAC
885    /// `mac`: Input buffer containing the MAC to check
886    ///
887    /// # Errors
888    ///
889    /// 1) `MacInvald`: If the computed MAC does not correspond to the value passed in `mac`.
890    ///
891    /// # Panics
892    ///
893    /// 1) If the algorithm is not a valid algorithm for `Mac`.
894    /// 2) If operation is not in active state.
895    /// 3) If input data exceeds maximum length for algorithm.
896    /// 4) Hardware or cryptographic algorithm failure.
897    /// 5) If the Implementation detects any other error.
898    pub fn compare_final(&self, message: &[u8], mac: &[u8]) -> Result<()> {
899        tee_check(unsafe {
900            raw::TEE_MACCompareFinal(
901                self.handle(),
902                message.as_ptr() as _,
903                message.len(),
904                mac.as_ptr() as _,
905                mac.len(),
906            )
907        })
908    }
909
910    /// Create a Mac operation without any specific algorithm or other data.
911    pub fn null() -> Self {
912        Self(OperationHandle::null())
913    }
914
915    /// Function usage is similar to [Digest::allocate](Digest::allocate).
916    pub fn allocate(algo: AlgorithmId, max_key_size: usize) -> Result<Self> {
917        match OperationHandle::allocate(algo, OperationMode::Mac, max_key_size) {
918            Ok(handle) => Ok(Self(handle)),
919            Err(e) => Err(e),
920        }
921    }
922
923    /// Function usage is similar to [Digest::info](Digest::info).
924    pub fn info(&self) -> OperationInfo {
925        self.0.info()
926    }
927
928    /// Function usage is similar to [Digest::info_multiple](Digest::info_multiple).
929    pub fn info_multiple(&self, info_buf: &mut [u8]) -> Result<OperationInfoMultiple> {
930        self.0.info_multiple(info_buf)
931    }
932
933    /// Function usage is similar to [Digest::reset](Digest::reset).
934    pub fn reset(&mut self) {
935        self.0.reset()
936    }
937
938    /// Function usage is similar to [Cipher::set_key](Cipher::set_key).
939    pub fn set_key<T: GenericObject>(&self, object: &T) -> Result<()> {
940        self.0.set_key(object)
941    }
942
943    /// Function usage is similar to [Digest::copy](Digest::copy).
944    pub fn copy<T: OpHandle>(&mut self, src: &T) {
945        self.0.copy(src)
946    }
947}
948
949impl OpHandle for Mac {
950    fn handle(&self) -> raw::TEE_OperationHandle {
951        self.0.handle()
952    }
953}
954
955/// An operation for conducting authenticated encryption / decryption.
956pub struct AE(OperationHandle);
957
958impl AE {
959    /// Initialize an AE opeartion.
960    /// The operation must be in the initial state and remains in the initial state afterwards.
961    ///
962    /// # Parameters
963    ///
964    /// 1) `nonce`: The peration nonce or IV
965    /// 2) `tag_len`: Size in bits of the tag:
966    ///    2.1) for `AES-GCM`, can be 128, 120, 112, 104, or 96;
967    ///    2.2) for `AES-CCM`, can be 128, 112, 96, 80, 64, 48, or 32.
968    /// 3) `aad_len`: length in bytes of the AAD (Used only for AES-CCM. Ignored for AES-GCM).
969    /// 4) `pay_load_len`: Length in bytes of the payload (Used only for AES-CCM. Ignored for AES-GCM).
970    ///
971    /// # Errors
972    ///
973    /// 1) `NotSupported`: If the `tag_len` is not supported by the algorithm.
974    ///
975    /// # Panics
976    ///
977    /// 1) If the algorithm is not a valid algorithm for `AE`.
978    /// 2) If no key is programmed in the operation.
979    /// 3) If the nonce length is not compatible with the length required by the algorithm.
980    /// 4) If operation is not in initial state.
981    /// 5) Hardware or cryptographic algorithm failure.
982    /// 6) If the Implementation detects any other error.
983    pub fn init(
984        &self,
985        nonce: &[u8],
986        tag_len: usize,
987        aad_len: usize,
988        pay_load_len: usize,
989    ) -> Result<()> {
990        tee_check(unsafe {
991            raw::TEE_AEInit(
992                self.handle(),
993                nonce.as_ptr() as _,
994                nonce.len(),
995                tag_len as u32,
996                aad_len,
997                pay_load_len,
998            )
999        })
1000    }
1001
1002    /// Feed a new chunk of Additional Authentication Data (AAD) to the AE operation.
1003    /// Subsequent calls to this function are possible.
1004    /// The operation SHALL be in initial state and remains in initial state afterwards.
1005    ///
1006    /// # Parameters
1007    ///
1008    /// 1) `aad_data`: Input buffer containing the chunk of AAD.
1009    ///
1010    /// # Panics
1011    ///
1012    /// 1) If the algorithm is not a valid algorithm for `AE`.
1013    /// 2) If the function is called before [init](AE::init) or has been finalized.
1014    /// 3) For `AES-CCM`, if the `aad_data.len()` exceeds the requirement.
1015    /// 4) If operation is not in initial state.
1016    /// 5) Hardware or cryptographic algorithm failure.
1017    /// 6) If the Implementation detects any other error.
1018    pub fn update_aad(&self, aad_data: &[u8]) {
1019        unsafe { raw::TEE_AEUpdateAAD(self.handle(), aad_data.as_ptr() as _, aad_data.len()) };
1020    }
1021
1022    /// Accumulate data for an Authentication Encryption operation.
1023    /// Input data does not have to be a multiple of block size. Subsequent calls to this function are possible.
1024    /// Unless one or more calls of this function have supplied sufficient input data, no output is generated.
1025    /// The buffers `src` and `dest` SHALL be either completely disjoint or equal in their starting positions.
1026    /// The operation may be in either initial or active state and enters active state afterwards if `src.len()` != 0.
1027    ///
1028    /// # Parameters
1029    ///
1030    /// 1) `src`: Input data buffer to be encrypted or decrypted.
1031    /// 2) `dest`: Output buffer.
1032    ///
1033    /// # Errors
1034    ///
1035    /// `ShortBuffer`: If the output buffer is not large enough to contain the output.
1036    ///
1037    /// # Panics
1038    ///
1039    /// 1) If the algorithm is not a valid algorithm for `AE`.
1040    /// 2) If the function is called before [init](AE::init) or has been finalized.
1041    /// 3) For `AES-CCM`, if the AAD length exceeds the requirement.
1042    /// 4) For `AES-CCM`, if the payload length is exceeds the requirement.
1043    /// 5) Hardware or cryptographic algorithm failure.
1044    /// 6) If the Implementation detects any other error.
1045    pub fn update(&self, src: &[u8], dest: &mut [u8]) -> Result<usize> {
1046        let mut dest_size: usize = dest.len();
1047        tee_check(unsafe {
1048            raw::TEE_AEUpdate(
1049                self.handle(),
1050                src.as_ptr() as _,
1051                src.len(),
1052                dest.as_mut_ptr() as _,
1053                &mut dest_size,
1054            )
1055        })?;
1056        Ok(dest_size)
1057    }
1058    /// Process data that has not been processed by previous calls to [update](AE::update) as well as data supplied in `src`.
1059    /// It completes the AE operation and computes the tag.
1060    /// The buffers `src` and `dest` SHALL be either completely disjoint or equal in their starting positions.
1061    /// The operation may be in either initial or active state and enters initial state afterwards.
1062    ///
1063    /// # Parameters
1064    ///
1065    /// 1) `src`: Reference to final chunk of input data to be encrypted.
1066    /// 2) `dest`: Output buffer. Can be omitted if the output is to be discarded, e.g. because it is known to be empty.
1067    /// 3) `tag`: Output buffer filled with the computed tag.
1068    ///
1069    /// # Example
1070    ///
1071    /// ``` rust,no_run
1072    /// # use optee_utee::{AE, AlgorithmId, OperationMode, AttributeMemref, AttributeId};
1073    /// # use optee_utee::{TransientObject, TransientObjectType};
1074    /// # fn main() -> optee_utee::Result<()> {
1075    /// let key = [0xa5u8; 16];
1076    /// let nonce = [0x00u8; 16];
1077    /// let aad = [0xffu8; 16];
1078    /// let clear1 = [0x5au8; 19];
1079    /// let clear2 = [0xa5u8; 13];
1080    /// let mut ciph1 = [0x00u8; 16];
1081    /// let mut ciph2 = [0x00u8; 16];
1082    /// let mut tag = [0x00u8; 16];
1083    /// match AE::allocate(AlgorithmId::AesCcm, OperationMode::Encrypt, 128) {
1084    ///     Ok(operation) => {
1085    ///         match TransientObject::allocate(TransientObjectType::Aes, 128) {
1086    ///             Ok(mut key_object) => {
1087    ///                 let attr = AttributeMemref::from_ref(AttributeId::SecretValue, &key);
1088    ///                 key_object.populate(&[attr.into()])?;
1089    ///                 operation.set_key(&key_object)?;
1090    ///                 operation.init(&nonce, 128, 16, 32)?;
1091    ///                 operation.update_aad(&aad);
1092    ///                 operation.update(&clear1, &mut ciph1)?;
1093    ///                 match operation.encrypt_final(&clear2, &mut ciph2, &mut tag) {
1094    ///                     Ok((_ciph_len, _tag_len)) => {
1095    ///                         // ...
1096    ///                         Ok(())
1097    ///                     },
1098    ///                     Err(e) => Err(e),
1099    ///                 }
1100    ///             },
1101    ///             Err(e) => Err(e),
1102    ///         }
1103    ///     },
1104    ///     Err(e) => Err(e),
1105    /// }
1106    /// # }
1107    /// ```
1108    ///
1109    /// # Errors
1110    ///
1111    /// `ShortBuffer`: If the output tag buffer is not large enough to contain the output.
1112    ///
1113    /// # Panics
1114    ///
1115    /// 1) If the algorithm is not a valid algorithm for `AE`.
1116    /// 2) If the function is called before [init](AE::init) or has been finalized.
1117    /// 3) If the required payload length is known but has not been provided.
1118    /// 4) Hardware or cryptographic algorithm failure.
1119    /// 5) If the Implementation detects any other error.
1120    // both dest and tag are updated with different size
1121    pub fn encrypt_final(
1122        &self,
1123        src: &[u8],
1124        dest: &mut [u8],
1125        tag: &mut [u8],
1126    ) -> Result<(usize, usize)> {
1127        let mut dest_size: usize = dest.len();
1128        let mut tag_size: usize = tag.len();
1129        tee_check(unsafe {
1130            raw::TEE_AEEncryptFinal(
1131                self.handle(),
1132                src.as_ptr() as _,
1133                src.len(),
1134                dest.as_mut_ptr() as _,
1135                &mut dest_size,
1136                tag.as_mut_ptr() as _,
1137                &mut tag_size,
1138            )
1139        })?;
1140        Ok((dest_size, tag_size))
1141    }
1142
1143    /// Process data that has not been processed by previous calls to [update](AE::update) as well as data supplied in `src`.
1144    /// It completes the AE operation and computes the tag.
1145    /// The buffers `src` and `dest` SHALL be either completely disjoint or equal in their starting positions.
1146    /// The operation may be in either initial or active state and enters initial state afterwards.
1147    ///
1148    /// # Parameters
1149    ///
1150    /// 1) `src`: Reference to final chunk of input data to be decrypted.
1151    /// 2) `dest`: Output buffer. Can be omitted if the output is to be discarded, e.g. because it is known to be empty.
1152    /// 3) `tag`: Input buffer containing the tag to compare.
1153    ///
1154    /// # Errors
1155    ///
1156    /// `ShortBuffer`: If the output buffer is not large enough to contain the output.
1157    /// `MacInvalid`: If the computed tag does not match the supplied tag.
1158    ///
1159    /// # Panics
1160    ///
1161    /// 1) If the algorithm is not a valid algorithm for `AE`.
1162    /// 2) If the function is called before [init](AE::init) or has been finalized.
1163    /// 3) If the required payload length is known but has not been provided.
1164    /// 4) Hardware or cryptographic algorithm failure.
1165    /// 5) If the Implementation detects any other error.
1166    pub fn decrypt_final(&self, src: &[u8], dest: &mut [u8], tag: &[u8]) -> Result<usize> {
1167        let mut dest_size: usize = dest.len();
1168        tee_check(unsafe {
1169            raw::TEE_AEDecryptFinal(
1170                self.handle(),
1171                src.as_ptr() as _,
1172                src.len(),
1173                dest.as_mut_ptr() as _,
1174                &mut dest_size,
1175                tag.as_ptr() as _,
1176                tag.len(),
1177            )
1178        })?;
1179        Ok(dest_size)
1180    }
1181
1182    /// Create an AE operation without any specific algorithm or other data.
1183    pub fn null() -> Self {
1184        Self(OperationHandle::null())
1185    }
1186
1187    /// Function usage is similar to [Digest::allocate](Digest::allocate).
1188    pub fn allocate(algo: AlgorithmId, mode: OperationMode, max_key_size: usize) -> Result<Self> {
1189        match OperationHandle::allocate(algo, mode, max_key_size) {
1190            Ok(handle) => Ok(Self(handle)),
1191            Err(e) => Err(e),
1192        }
1193    }
1194
1195    /// Function usage is similar to [Digest::info](Digest::info).
1196    pub fn info(&self) -> OperationInfo {
1197        self.0.info()
1198    }
1199
1200    /// Function usage is similar to [Digest::info_multiple](Digest::info_multiple).
1201    pub fn info_multiple(&self, info_buf: &mut [u8]) -> Result<OperationInfoMultiple> {
1202        self.0.info_multiple(info_buf)
1203    }
1204
1205    /// Function usage is similar to [Digest::reset](Digest::reset).
1206    pub fn reset(&mut self) {
1207        self.0.reset()
1208    }
1209
1210    /// Function usage is similar to [Cipher::set_key](Cipher::set_key).
1211    pub fn set_key<T: GenericObject>(&self, object: &T) -> Result<()> {
1212        self.0.set_key(object)
1213    }
1214
1215    /// Function usage is similar to [Digest::copy](Digest::copy).
1216    pub fn copy<T: OpHandle>(&mut self, src: &T) {
1217        self.0.copy(src)
1218    }
1219}
1220
1221impl OpHandle for AE {
1222    fn handle(&self) -> raw::TEE_OperationHandle {
1223        self.0.handle()
1224    }
1225}
1226
1227/// An operation for conducting asymmetric encryption /decryption or asymmetric sign / verify.
1228/// Note that asymmetric encryption is always “single-stage”,
1229/// which differs from [Cipher](Cipher) which are always “multi-stage”.
1230pub struct Asymmetric(OperationHandle);
1231
1232impl Asymmetric {
1233    /// Encrypt a message.
1234    ///
1235    /// # Parameters
1236    ///
1237    /// 1) `params`: Optional operation parameters.
1238    /// 2) `src`: Input plaintext buffer.
1239    ///
1240    /// # Example
1241    /// ``` rust,no_run
1242    /// # use optee_utee::{TransientObject, TransientObjectType, Asymmetric};
1243    /// # use optee_utee::{AlgorithmId, OperationMode};
1244    /// # fn main() -> optee_utee::Result<()> {
1245    /// let clear = [1u8; 8];
1246    /// match TransientObject::allocate(TransientObjectType::RsaKeypair, 256) {
1247    ///     Ok(key) => {
1248    ///         key.generate_key(256, &[])?;
1249    ///         match Asymmetric::allocate(
1250    ///             AlgorithmId::RsaesPkcs1V15,
1251    ///             OperationMode::Encrypt,
1252    ///             256) {
1253    ///             Ok(mut operation) => {
1254    ///                 operation.set_key(&key)?;
1255    ///                 match operation.encrypt(&[], &clear) {
1256    ///                     Ok(ciph_text) => {
1257    ///                         // Get cipher text as a vector
1258    ///                         // ...
1259    ///                         Ok(())
1260    ///                     }
1261    ///                     Err(e) => Err(e),
1262    ///                 }
1263    ///             }
1264    ///             Err(e) => Err(e),
1265    ///         }
1266    ///     }
1267    ///     Err(e) => Err(e),
1268    /// }
1269    /// # }
1270    /// ```
1271    ///
1272    /// # Errors
1273    ///
1274    /// 1) `ShortBuffer`: If the output buffer is not large enough to hold the result.
1275    /// 2) `BadParameters`: If the length of the input buffer is not consistent with the algorithm or key size.
1276    /// 3) `CiphertextInvalid`: If there is an error in the packing used on the ciphertext.
1277    ///
1278    /// # Panics
1279    ///
1280    /// 1) If the algorithm is not a valid algorithm for [Encrypt](OperationMode::Encrypt] of
1281    ///    `Asymmetric`.
1282    /// 2) If no key is programmed in the operation.
1283    /// 3) Hardware or cryptographic algorithm failure.
1284    /// 4) If the Implementation detects any other error.
1285    // This function can update output size with short buffer error when buffer is too
1286    // short, and example acipher utilizes this feature!
1287    // Define this function as unsafe because we need to return Ok for short buffer error.
1288    pub fn encrypt(&self, params: &[Attribute], src: &[u8]) -> Result<Vec<u8>> {
1289        let p: Vec<raw::TEE_Attribute> = params.iter().map(|p| p.raw()).collect();
1290        let mut res_size: usize = self.info().key_size() as usize;
1291        let mut res_vec: Vec<u8> = vec![0u8; res_size];
1292        tee_check(unsafe {
1293            raw::TEE_AsymmetricEncrypt(
1294                self.handle(),
1295                p.as_ptr() as _,
1296                params.len() as u32,
1297                src.as_ptr() as _,
1298                src.len(),
1299                res_vec.as_mut_ptr() as _,
1300                &mut res_size,
1301            )
1302        })?;
1303        res_vec.truncate(res_size);
1304        Ok(res_vec)
1305    }
1306
1307    /// Decrypt a message.
1308    ///
1309    /// # Parameters
1310    ///
1311    /// 1) `params`: Optional operation parameters.
1312    /// 2) `src`: Input ciphertext buffer.
1313    ///
1314    /// # Errors
1315    ///
1316    /// 1) `ShortBuffer`: If the output buffer is not large enough to hold the result.
1317    /// 2) `BadParameters`: If the length of the input buffer is not consistent with the algorithm or key size.
1318    /// 3) `CiphertextInvalid`: If there is an error in the packing used on the ciphertext.
1319    ///
1320    /// # Panics
1321    ///
1322    /// 1) If the algorithm is not a valid algorithm for [Decrypt](OperationMode::Decrypt] of
1323    ///    `Asymmetric`.
1324    /// 2) If no key is programmed in the operation.
1325    /// 3) Hardware or cryptographic algorithm failure.
1326    /// 4) If the Implementation detects any other error.
1327    pub fn decrypt(&self, params: &[Attribute], src: &[u8]) -> Result<Vec<u8>> {
1328        let p: Vec<raw::TEE_Attribute> = params.iter().map(|p| p.raw()).collect();
1329        let mut res_size: usize = self.info().key_size() as usize;
1330        let mut res_vec: Vec<u8> = vec![0u8; res_size];
1331        tee_check(unsafe {
1332            raw::TEE_AsymmetricDecrypt(
1333                self.handle(),
1334                p.as_ptr() as _,
1335                params.len() as u32,
1336                src.as_ptr() as _,
1337                src.len(),
1338                res_vec.as_mut_ptr() as _,
1339                &mut res_size,
1340            )
1341        })?;
1342        res_vec.truncate(res_size);
1343        Ok(res_vec)
1344    }
1345
1346    /// Sign a message digest.
1347    ///
1348    /// # Parameters
1349    ///
1350    /// 1) `params`: Optional operation parameters.
1351    /// 2) `digest`: Input buffer containing the input message digest.
1352    /// 3) `signature`: Output buffer written with the signature of the digest.
1353    ///
1354    /// # Errors
1355    ///
1356    /// 1) `ShortBuffer`: If `signature` is not large enough to hold the result.
1357    ///
1358    /// # Panics
1359    ///
1360    /// 1) If the algorithm is not a valid algorithm for [Sign](OperationMode::Sign] of
1361    ///    `Asymmetric`.
1362    /// 2) If no key is programmed in the operation.
1363    /// 3) If the mode is not set as [Sign](OperationMode::Sign].
1364    /// 4) If `digest.len()` is not equal to the hash size of the algorithm.
1365    /// 3) Hardware or cryptographic algorithm failure.
1366    /// 4) If the Implementation detects any other error.
1367    pub fn sign_digest(
1368        &self,
1369        params: &[Attribute],
1370        digest: &[u8],
1371        signature: &mut [u8],
1372    ) -> Result<usize> {
1373        let p: Vec<raw::TEE_Attribute> = params.iter().map(|p| p.raw()).collect();
1374        let mut signature_size: usize = signature.len();
1375        tee_check(unsafe {
1376            raw::TEE_AsymmetricSignDigest(
1377                self.handle(),
1378                p.as_ptr() as _,
1379                params.len() as u32,
1380                digest.as_ptr() as _,
1381                digest.len(),
1382                signature.as_mut_ptr() as _,
1383                &mut signature_size,
1384            )
1385        })?;
1386        Ok(signature_size)
1387    }
1388
1389    /// Verify a message digest.
1390    ///
1391    /// # Parameters
1392    ///
1393    /// 1) `params`: Optional operation parameters.
1394    /// 2) `digest`: Input buffer containing the input message digest.
1395    /// 3) `signature`: Input buffer containing the signature to verify.
1396    ///
1397    /// # Errors
1398    ///
1399    /// 1) `SignatureInvalid`: If the signature is invalid.
1400    ///
1401    /// # Panics
1402    ///
1403    /// 1) If the algorithm is not a valid algorithm for [Verify](OperationMode::Verify] of
1404    ///    `Asymmetric`.
1405    /// 2) If no key is programmed in the operation.
1406    /// 3) If the mode is not set as [Verify](OperationMode::Verify].
1407    /// 4) If `digest.len()` is not equal to the hash size of the algorithm.
1408    /// 3) Hardware or cryptographic algorithm failure.
1409    /// 4) If the Implementation detects any other error.
1410    pub fn verify_digest(
1411        &self,
1412        params: &[Attribute],
1413        digest: &[u8],
1414        signature: &[u8],
1415    ) -> Result<()> {
1416        let p: Vec<raw::TEE_Attribute> = params.iter().map(|p| p.raw()).collect();
1417        tee_check(unsafe {
1418            raw::TEE_AsymmetricVerifyDigest(
1419                self.handle(),
1420                p.as_ptr() as _,
1421                params.len() as u32,
1422                digest.as_ptr() as _,
1423                digest.len(),
1424                signature.as_ptr() as _,
1425                signature.len(),
1426            )
1427        })
1428    }
1429
1430    /// Create an Asymmetric operation without any specific algorithm or other data.
1431    pub fn null() -> Self {
1432        Self(OperationHandle::null())
1433    }
1434
1435    /// Function usage is similar to [Digest::allocate](Digest::allocate).
1436    pub fn allocate(algo: AlgorithmId, mode: OperationMode, max_key_size: usize) -> Result<Self> {
1437        match OperationHandle::allocate(algo, mode, max_key_size) {
1438            Ok(handle) => Ok(Self(handle)),
1439            Err(e) => Err(e),
1440        }
1441    }
1442
1443    /// Function usage is similar to [Digest::info](Digest::info).
1444    pub fn info(&self) -> OperationInfo {
1445        self.0.info()
1446    }
1447
1448    /// Function usage is similar to [Digest::info_multiple](Digest::info_multiple).
1449    pub fn info_multiple(&self, info_buf: &mut [u8]) -> Result<OperationInfoMultiple> {
1450        self.0.info_multiple(info_buf)
1451    }
1452
1453    /// Function usage is similar to [Cipher::set_key](Cipher::set_key).
1454    pub fn set_key<T: GenericObject>(&mut self, object: &T) -> Result<()> {
1455        self.0.set_key(object)
1456    }
1457
1458    /// Function usage is similar to [Digest::copy](Digest::copy).
1459    pub fn copy<T: OpHandle>(&mut self, src: &T) {
1460        self.0.copy(src)
1461    }
1462}
1463
1464impl OpHandle for Asymmetric {
1465    fn handle(&self) -> raw::TEE_OperationHandle {
1466        self.0.handle()
1467    }
1468}
1469
1470/// An operation for derive a shared key object.
1471pub struct DeriveKey(OperationHandle);
1472
1473impl DeriveKey {
1474    /// Take one of the key derivation algorithms that supports this operation as
1475    /// defined in [AlgorithmId](AlgorithmId), and output a key object.
1476    ///
1477    /// # Parameters
1478    ///
1479    /// 1) `params`: For algorithm [DhDeriveSharedSecret][AlgorithmId::DhDeriveSharedSecret],
1480    ///    [DhPublicValue](../object/enum.AttributeId.html#variant.DhPublicValue) is required as
1481    ///    the passed in attribute. For the PBKDF2-HMAC algorithms
1482    ///    ([Pbkdf2HmacSha1][AlgorithmId::Pbkdf2HmacSha1] and similar), pass the
1483    ///    salt, the iteration count and the derived key material length as
1484    ///    attributes, and use a
1485    ///    [Pbkdf2Password](crate::TransientObjectType::Pbkdf2Password) object
1486    ///    as the operation key.
1487    /// 2) `object`: An uninitialized transient object to be filled with the derived key.
1488    ///
1489    /// # Example
1490    ///
1491    /// ``` rust,no_run
1492    /// # use optee_utee::{AttributeMemref, AttributeId, TransientObject, TransientObjectType};
1493    /// # use optee_utee::{DeriveKey, AlgorithmId, GenericObject};
1494    /// # fn example1() -> optee_utee::Result<()> {
1495    ///
1496    /// let attr_prime = AttributeMemref::from_ref(AttributeId::DhPrime, &[23u8]);
1497    /// let attr_base = AttributeMemref::from_ref(AttributeId::DhBase, &[5u8]);
1498    /// let mut public_1 = [0u8; 32];
1499    /// match TransientObject::allocate(TransientObjectType::DhKeypair, 256) {
1500    ///     Ok(key_pair_1) => {
1501    ///         key_pair_1.generate_key(256, &[attr_prime.into(), attr_base.into()])?;
1502    ///         key_pair_1.ref_attribute(AttributeId::DhPublicValue, &mut public_1)?;
1503    ///         Ok(())
1504    ///     }
1505    ///     Err(e) => Err(e),
1506    /// }
1507    /// # }
1508    ///
1509    /// # fn example2() -> optee_utee::Result<()> {
1510    /// # let mut public_1 = [0u8; 32];
1511    ///
1512    /// let attr_prime = AttributeMemref::from_ref(AttributeId::DhPrime, &[23u8]);
1513    /// let attr_base = AttributeMemref::from_ref(AttributeId::DhBase, &[5u8]);
1514    /// match TransientObject::allocate(TransientObjectType::DhKeypair, 256) {
1515    ///     Ok(key_pair_2) => {
1516    ///         key_pair_2.generate_key(256, &[attr_prime.into(), attr_base.into()])?;
1517    ///         match DeriveKey::allocate(AlgorithmId::DhDeriveSharedSecret, 256) {
1518    ///             Ok(mut operation) => {
1519    ///                 operation.set_key(&key_pair_2)?;
1520    ///                 match TransientObject::allocate(TransientObjectType::GenericSecret, 256) {
1521    ///                     // Derived key is saved as an transient object
1522    ///                     Ok(mut derived_key) => {
1523    ///                         let attr_public = AttributeMemref::from_ref(AttributeId::DhPublicValue, &public_1);
1524    ///                         operation.derive(&[attr_public.into()], &mut derived_key);
1525    ///                         // ...
1526    ///                         Ok(())
1527    ///                     }
1528    ///                     Err(e) => Err(e),
1529    ///                 }
1530    ///             }
1531    ///             Err(e) => Err(e),
1532    ///         }
1533    ///     }
1534    ///     Err(e) => Err(e),
1535    /// }
1536    /// # }
1537    /// ```
1538    ///
1539    /// # Panics
1540    ///
1541    /// 1) If the algorithm is not a valid algorithm for `DeriveKey`.
1542    /// 2) If the `object` is too small for generated value.
1543    /// 3) If no key is programmed in the operation.
1544    /// 4) Hardware or cryptographic algorithm failure.
1545    /// 5) If the Implementation detects any other error.
1546    pub fn derive(&self, params: &[Attribute], object: &mut TransientObject) {
1547        let p: Vec<raw::TEE_Attribute> = params.iter().map(|p| p.raw()).collect();
1548        unsafe {
1549            raw::TEE_DeriveKey(
1550                self.handle(),
1551                p.as_ptr() as _,
1552                params.len() as u32,
1553                *object.as_raw_ref(),
1554            )
1555        };
1556    }
1557
1558    /// Create a DeriveKey operation without any specific algorithm or other data.
1559    pub fn null() -> Self {
1560        Self(OperationHandle::null())
1561    }
1562
1563    /// Function usage is similar to [Digest::allocate](Digest::allocate).
1564    /// Currently supports [DhDeriveSharedSecret][AlgorithmId::DhDeriveSharedSecret],
1565    /// [EcDhDeriveSharedSecret][AlgorithmId::EcDhDeriveSharedSecret],
1566    /// [X25519][AlgorithmId::X25519] and the PBKDF2-HMAC algorithms as
1567    /// `algo`.
1568    pub fn allocate(algo: AlgorithmId, max_key_size: usize) -> Result<Self> {
1569        match OperationHandle::allocate(algo, OperationMode::Derive, max_key_size) {
1570            Ok(handle) => Ok(Self(handle)),
1571            Err(e) => Err(e),
1572        }
1573    }
1574
1575    /// Function usage is similar to [Digest::info](Digest::info).
1576    pub fn info(&self) -> OperationInfo {
1577        self.0.info()
1578    }
1579
1580    /// Function usage is similar to [Digest::info_multiple](Digest::info_multiple).
1581    pub fn info_multiple(&self, info_buf: &mut [u8]) -> Result<OperationInfoMultiple> {
1582        self.0.info_multiple(info_buf)
1583    }
1584
1585    /// Function usage is similar to [Cipher::set_key](Cipher::set_key).
1586    pub fn set_key<T: GenericObject>(&mut self, object: &T) -> Result<()> {
1587        self.0.set_key(object)
1588    }
1589
1590    /// Function usage is similar to [Cipher::set_key_2](Cipher::set_key_2).
1591    pub fn set_key_2<T: GenericObject, D: GenericObject>(
1592        &self,
1593        object1: &T,
1594        object2: &D,
1595    ) -> Result<()> {
1596        self.0.set_key_2(object1, object2)
1597    }
1598
1599    /// Function usage is similar to [Digest::copy](Digest::copy).
1600    pub fn copy<T: OpHandle>(&mut self, src: &T) {
1601        self.0.copy(src)
1602    }
1603}
1604
1605impl OpHandle for DeriveKey {
1606    fn handle(&self) -> raw::TEE_OperationHandle {
1607        self.0.handle()
1608    }
1609}
1610
1611/// An operation for generating random data.
1612pub struct Random();
1613
1614impl Random {
1615    /// Generate random data.
1616    ///
1617    /// # Parameters
1618    ///
1619    /// 1) `res_buffer`: Reference to generated random data
1620    ///
1621    /// # Example
1622    ///
1623    /// ``` rust,no_run
1624    /// # use optee_utee::Random;
1625    /// let mut res = [0u8;16];
1626    /// Random::generate(&mut res);
1627    /// ```
1628    ///
1629    /// # Panics
1630    ///
1631    /// 1) Hardware or cryptographic algorithm failure.
1632    /// 2) If the Implementation detects any other error.
1633    pub fn generate(res_buffer: &mut [u8]) {
1634        unsafe {
1635            raw::TEE_GenerateRandom(res_buffer.as_mut_ptr() as _, res_buffer.len() as _);
1636        }
1637    }
1638}
1639
1640/// Algorithms that can be allocated as an crypto operation.
1641#[derive(Clone, Copy, strum::Display)]
1642#[repr(u32)]
1643pub enum AlgorithmId {
1644    /// [Cipher](Cipher) supported algorithm.
1645    AesEcbNopad = 0x10000010,
1646    /// [Cipher](Cipher) supported algorithm.
1647    AesCbcNopad = 0x10000110,
1648    /// [Cipher](Cipher) supported algorithm.
1649    AesCtr = 0x10000210,
1650    /// [Cipher](Cipher) supported algorithm.
1651    AesCts = 0x10000310,
1652    /// [Cipher](Cipher) supported algorithm.
1653    AesXts = 0x10000410,
1654    /// [Mac](Mac) supported algorithm.
1655    AesCbcMacNopad = 0x30000110,
1656    /// [Mac](Mac) supported algorithm.
1657    AesCbcMacPkcs5 = 0x30000510,
1658    /// [Mac](Mac) supported algorithm.
1659    AesCmac = 0x30000610,
1660    /// [AE](AE) supported algorithm.
1661    AesCcm = 0x40000710,
1662    /// [AE](AE) supported algorithm.
1663    AesGcm = 0x40000810,
1664    /// [Cipher](Cipher) supported algorithm.
1665    DesEcbNopad = 0x10000011,
1666    /// [Cipher](Cipher) supported algorithm.
1667    DesCbcNopad = 0x10000111,
1668    /// [Mac](Mac) supported algorithm.
1669    DesCbcMacNopad = 0x30000111,
1670    /// [Mac](Mac) supported algorithm.
1671    DesCbcMacPkcs5 = 0x30000511,
1672    /// [Cipher](Cipher) supported algorithm.
1673    Des3EcbNopad = 0x10000013,
1674    /// [Cipher](Cipher) supported algorithm.
1675    Des3CbcNopad = 0x10000113,
1676    /// [Mac](Mac) supported algorithm.
1677    Des3CbcMacNopad = 0x30000113,
1678    /// [Mac](Mac) supported algorithm.
1679    Des3CbcMacPkcs5 = 0x30000513,
1680    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1681    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1682    RsassaPkcs1V15 = 0xF0000830,
1683    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1684    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1685    RsassaPkcs1V15MD5 = 0x70001830,
1686    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1687    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1688    RsassaPkcs1V15Sha1 = 0x70002830,
1689    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1690    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1691    RsassaPkcs1V15Sha224 = 0x70003830,
1692    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1693    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1694    RsassaPkcs1V15Sha256 = 0x70004830,
1695    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1696    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1697    RsassaPkcs1V15Sha384 = 0x70005830,
1698    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1699    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1700    RsassaPkcs1V15Sha512 = 0x70006830,
1701    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1702    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1703    RsassaPkcs1V15MD5Sha1 = 0x7000F830,
1704    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1705    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1706    RsassaPkcs1PssMgf1MD5 = 0xF0111930,
1707    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1708    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1709    RsassaPkcs1PssMgf1Sha1 = 0x70212930,
1710    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1711    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1712    RsassaPkcs1PssMgf1Sha224 = 0x70313930,
1713    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1714    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1715    RsassaPkcs1PssMgf1Sha256 = 0x70414930,
1716    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1717    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1718    RsassaPkcs1PssMgf1Sha384 = 0x70515930,
1719    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1720    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1721    RsassaPkcs1PssMgf1Sha512 = 0x70616930,
1722    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1723    /// [Encrypt](OperationMode::Encrypt) or [Decrypt](OperationMode::Decrypt) mode.
1724    RsaesPkcs1V15 = 0x60000130,
1725    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1726    /// [Encrypt](OperationMode::Encrypt) or [Decrypt](OperationMode::Decrypt) mode.
1727    RsaesPkcs1OAepMgf1MD5 = 0xF0110230,
1728    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1729    /// [Encrypt](OperationMode::Encrypt) or [Decrypt](OperationMode::Decrypt) mode.
1730    RsaesPkcs1OAepMgf1Sha1 = 0x60210230,
1731    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1732    /// [Encrypt](OperationMode::Encrypt) or [Decrypt](OperationMode::Decrypt) mode.
1733    RsaesPkcs1OAepMgf1Sha224 = 0x60310230,
1734    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1735    /// [Encrypt](OperationMode::Encrypt) or [Decrypt](OperationMode::Decrypt) mode.
1736    RsaesPkcs1OAepMgf1Sha256 = 0x60410230,
1737    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1738    /// [Encrypt](OperationMode::Encrypt) or [Decrypt](OperationMode::Decrypt) mode.
1739    RsaesPkcs1OAepMgf1Sha384 = 0x60510230,
1740    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1741    /// [Encrypt](OperationMode::Encrypt) or [Decrypt](OperationMode::Decrypt) mode.
1742    RsaesPkcs1OAepMgf1Sha512 = 0x60610230,
1743    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1744    /// [Encrypt](OperationMode::Encrypt) or [Decrypt](OperationMode::Decrypt) mode.
1745    RsaNopad = 0x60000030,
1746    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1747    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1748    DSASha1 = 0x70002131,
1749    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1750    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1751    DSASha224 = 0x70003131,
1752    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1753    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1754    DSASha256 = 0x70004131,
1755    /// [DeriveKey](DeriveKey) supported algorithm.
1756    DhDeriveSharedSecret = 0x80000032,
1757    /// [DeriveKey](DeriveKey) supported algorithm.
1758    EcDhDeriveSharedSecret = 0x80000042,
1759    /// [DeriveKey](DeriveKey) supported algorithm, PBKDF2 with HMAC-SHA1.
1760    Pbkdf2HmacSha1 = 0x800020C2,
1761    /// [DeriveKey](DeriveKey) supported algorithm, PBKDF2 with HMAC-SHA224.
1762    Pbkdf2HmacSha224 = 0x800030C2,
1763    /// [DeriveKey](DeriveKey) supported algorithm, PBKDF2 with HMAC-SHA256.
1764    Pbkdf2HmacSha256 = 0x800040C2,
1765    /// [DeriveKey](DeriveKey) supported algorithm, PBKDF2 with HMAC-SHA384.
1766    Pbkdf2HmacSha384 = 0x800050C2,
1767    /// [DeriveKey](DeriveKey) supported algorithm, PBKDF2 with HMAC-SHA512.
1768    Pbkdf2HmacSha512 = 0x800060C2,
1769    /// [DeriveKey](DeriveKey) supported algorithm, PBKDF2 with HMAC-SM3.
1770    Pbkdf2HmacSm3 = 0x800070C2,
1771    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1772    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1773    EcDsaSha1 = 0x70001042,
1774    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1775    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1776    EcDsaSha224 = 0x70002042,
1777    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1778    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1779    EcDsaSha256 = 0x70003042,
1780    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1781    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1782    EcDsaSha384 = 0x70004042,
1783    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1784    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1785    EcDsaSha512 = 0x70005042,
1786    /// [Asymmetric](Asymmetric) supported algorithm, can be applied with
1787    /// [Sign](OperationMode::Sign) or [Verify](OperationMode::Verify) mode.
1788    Ed25519 = 0x70006043,
1789    /// [DeriveKey](DeriveKey) supported algorithm.
1790    X25519 = 0x80000044,
1791    /// [Digest](Digest) supported algorithm.
1792    Md5 = 0x50000001,
1793    /// [Digest](Digest) supported algorithm.
1794    Sha1 = 0x50000002,
1795    /// [Digest](Digest) supported algorithm.
1796    Sha224 = 0x50000003,
1797    /// [Digest](Digest) supported algorithm.
1798    Sha256 = 0x50000004,
1799    /// [Digest](Digest) supported algorithm.
1800    Sha384 = 0x50000005,
1801    /// [Digest](Digest) supported algorithm.
1802    Sha512 = 0x50000006,
1803    /// [Mac](Mac) supported algorithm.
1804    Md5Sha1 = 0x5000000F,
1805    /// [Mac](Mac) supported algorithm.
1806    HmacMd5 = 0x30000001,
1807    /// [Mac](Mac) supported algorithm.
1808    HmacSha1 = 0x30000002,
1809    /// [Mac](Mac) supported algorithm.
1810    HmacSha224 = 0x30000003,
1811    /// [Mac](Mac) supported algorithm.
1812    HmacSha256 = 0x30000004,
1813    /// [Mac](Mac) supported algorithm.
1814    HmacSha384 = 0x30000005,
1815    /// [Mac](Mac) supported algorithm.
1816    HmacSha512 = 0x30000006,
1817    /// Reserved for GlobalPlatform compliance test applications.
1818    IllegalValue = 0xefffffff,
1819}
1820
1821/// This specification defines support for optional cryptographic elements.
1822#[repr(u32)]
1823pub enum ElementId {
1824    /// Where algId fully defines the required support,
1825    /// the special value TEE_CRYPTO_ELEMENT_NONE should be used
1826    ElementNone = 0x00000000,
1827    /// Source: `NIST`, Generic: `Y`, Size: 192 bits
1828    EccCurveNistP192 = 0x00000001,
1829    /// Source: `NIST`, Generic: `Y`, Size: 224 bits
1830    EccCurveNistP224 = 0x00000002,
1831    /// Source: `NIST`, Generic: `Y`, Size: 256 bits
1832    EccCurveNistP256 = 0x00000003,
1833    /// Source: `NIST`, Generic: `Y`, Size: 384 bits
1834    EccCurveNistP384 = 0x00000004,
1835    /// Source: `NIST`, Generic: `Y`, Size: 521 bits
1836    EccCurveNistP521 = 0x00000005,
1837    /// Source: `IETF`, Generic: `N`, Size: 256 bits
1838    EccCurve25519 = 0x00000300,
1839}
1840
1841#[cfg(test)]
1842mod tests {
1843    use super::*;
1844    use crate::{AttributeId, TransientObjectType};
1845
1846    #[test]
1847    // Guarantee: every high-level PBKDF2 `AlgorithmId` variant maps 1:1
1848    // to the OP-TEE raw constant from `tee_api_defines_extensions.h`,
1849    // so `DeriveKey::allocate` passes the correct algorithm ID to
1850    // `TEE_AllocateOperation`.
1851    fn pbkdf2_algorithm_ids_match_raw_constants() {
1852        let cases = [
1853            (
1854                AlgorithmId::Pbkdf2HmacSha1,
1855                raw::TEE_ALG_PBKDF2_HMAC_SHA1_DERIVE_KEY,
1856            ),
1857            (
1858                AlgorithmId::Pbkdf2HmacSha224,
1859                raw::TEE_ALG_PBKDF2_HMAC_SHA224_DERIVE_KEY,
1860            ),
1861            (
1862                AlgorithmId::Pbkdf2HmacSha256,
1863                raw::TEE_ALG_PBKDF2_HMAC_SHA256_DERIVE_KEY,
1864            ),
1865            (
1866                AlgorithmId::Pbkdf2HmacSha384,
1867                raw::TEE_ALG_PBKDF2_HMAC_SHA384_DERIVE_KEY,
1868            ),
1869            (
1870                AlgorithmId::Pbkdf2HmacSha512,
1871                raw::TEE_ALG_PBKDF2_HMAC_SHA512_DERIVE_KEY,
1872            ),
1873            (
1874                AlgorithmId::Pbkdf2HmacSm3,
1875                raw::TEE_ALG_PBKDF2_HMAC_SM3_DERIVE_KEY,
1876            ),
1877        ];
1878        for (algo, expected) in cases {
1879            assert_eq!(algo as u32, expected, "algorithm ID mismatch for {algo}");
1880        }
1881    }
1882
1883    #[test]
1884    // Guarantee: the high-level PBKDF2 object type and attribute IDs map
1885    // 1:1 to the OP-TEE raw constants, so password objects and PBKDF2
1886    // operation parameters are built with the correct IDs.
1887    fn pbkdf2_object_and_attribute_ids_match_raw_constants() {
1888        let object_cases = [(
1889            TransientObjectType::Pbkdf2Password,
1890            raw::TEE_TYPE_PBKDF2_PASSWORD,
1891        )];
1892        for (obj_type, expected) in object_cases {
1893            assert_eq!(obj_type as u32, expected, "ID mismatch for {obj_type}");
1894        }
1895        let attr_cases = [
1896            (AttributeId::Pbkdf2Password, raw::TEE_ATTR_PBKDF2_PASSWORD),
1897            (AttributeId::Pbkdf2Salt, raw::TEE_ATTR_PBKDF2_SALT),
1898            (
1899                AttributeId::Pbkdf2IterationCount,
1900                raw::TEE_ATTR_PBKDF2_ITERATION_COUNT,
1901            ),
1902            (
1903                AttributeId::Pbkdf2DkmLength,
1904                raw::TEE_ATTR_PBKDF2_DKM_LENGTH,
1905            ),
1906        ];
1907        for (attr, expected) in attr_cases {
1908            assert_eq!(attr as u32, expected, "ID mismatch for {attr}");
1909        }
1910    }
1911}