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
// Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use crate::{
    handles::KeyHandle,
    structures::{Digest, HashcheckTicket, Signature, SignatureScheme, VerifiedTicket},
    tss2_esys::{Esys_Sign, Esys_VerifySignature},
    Context, Error, Result,
};
use log::error;
use std::convert::{TryFrom, TryInto};
use std::ptr::null_mut;

impl Context {
    /// Verify if a signature was generated by signing a given digest with a key in the TPM.
    pub fn verify_signature(
        &mut self,
        key_handle: KeyHandle,
        digest: Digest,
        signature: Signature,
    ) -> Result<VerifiedTicket> {
        let mut validation_ptr = null_mut();
        let ret = unsafe {
            Esys_VerifySignature(
                self.mut_context(),
                key_handle.into(),
                self.optional_session_1(),
                self.optional_session_2(),
                self.optional_session_3(),
                &digest.into(),
                &signature.try_into()?,
                &mut validation_ptr,
            )
        };
        let ret = Error::from_tss_rc(ret);

        if ret.is_success() {
            VerifiedTicket::try_from(Context::ffi_data_to_owned(validation_ptr))
        } else {
            error!("Error when verifying signature: {}", ret);
            Err(ret)
        }
    }

    /// Sign a digest with a key present in the TPM and return the signature.
    pub fn sign(
        &mut self,
        key_handle: KeyHandle,
        digest: Digest,
        scheme: SignatureScheme,
        validation: HashcheckTicket,
    ) -> Result<Signature> {
        let mut signature_ptr = null_mut();
        let ret = unsafe {
            Esys_Sign(
                self.mut_context(),
                key_handle.into(),
                self.required_session_1()?,
                self.optional_session_2(),
                self.optional_session_3(),
                &digest.into(),
                &scheme.into(),
                &validation.try_into()?,
                &mut signature_ptr,
            )
        };
        let ret = Error::from_tss_rc(ret);

        if ret.is_success() {
            Signature::try_from(Context::ffi_data_to_owned(signature_ptr))
        } else {
            error!("Error when signing: {}", ret);
            Err(ret)
        }
    }
}