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
// Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! Key management functions

use crate::error::{Result, Rv};
use crate::mechanism::Mechanism;
use crate::object::{Attribute, ObjectHandle};
use crate::session::Session;
use cryptoki_sys::{CK_ATTRIBUTE, CK_MECHANISM, CK_MECHANISM_PTR};
use std::convert::TryInto;

impl Session {
    /// Generate a secret key
    pub fn generate_key(
        &self,
        mechanism: &Mechanism,
        template: &[Attribute],
    ) -> Result<ObjectHandle> {
        let mut mechanism: CK_MECHANISM = mechanism.into();
        let mut template: Vec<CK_ATTRIBUTE> = template.iter().map(|attr| attr.into()).collect();
        let mut handle = 0;
        unsafe {
            Rv::from(get_pkcs11!(self.client(), C_GenerateKey)(
                self.handle(),
                &mut mechanism as CK_MECHANISM_PTR,
                template.as_mut_ptr(),
                template.len().try_into()?,
                &mut handle,
            ))
            .into_result()?;
        }

        Ok(ObjectHandle::new(handle))
    }

    /// Generate a public/private key pair
    pub fn generate_key_pair(
        &self,
        mechanism: &Mechanism,
        pub_key_template: &[Attribute],
        priv_key_template: &[Attribute],
    ) -> Result<(ObjectHandle, ObjectHandle)> {
        let mut mechanism: CK_MECHANISM = mechanism.into();
        let mut pub_key_template: Vec<CK_ATTRIBUTE> =
            pub_key_template.iter().map(|attr| attr.into()).collect();
        let mut priv_key_template: Vec<CK_ATTRIBUTE> =
            priv_key_template.iter().map(|attr| attr.into()).collect();
        let mut pub_handle = 0;
        let mut priv_handle = 0;
        unsafe {
            Rv::from(get_pkcs11!(self.client(), C_GenerateKeyPair)(
                self.handle(),
                &mut mechanism as CK_MECHANISM_PTR,
                pub_key_template.as_mut_ptr(),
                pub_key_template.len().try_into()?,
                priv_key_template.as_mut_ptr(),
                priv_key_template.len().try_into()?,
                &mut pub_handle,
                &mut priv_handle,
            ))
            .into_result()?;
        }

        Ok((
            ObjectHandle::new(pub_handle),
            ObjectHandle::new(priv_handle),
        ))
    }

    /// Derives a key from a base key
    pub fn derive_key(
        &self,
        mechanism: &Mechanism,
        base_key: ObjectHandle,
        template: &[Attribute],
    ) -> Result<ObjectHandle> {
        let mut mechanism: CK_MECHANISM = mechanism.into();
        let mut template: Vec<CK_ATTRIBUTE> = template.iter().map(|attr| attr.into()).collect();
        let mut handle = 0;
        unsafe {
            Rv::from(get_pkcs11!(self.client(), C_DeriveKey)(
                self.handle(),
                &mut mechanism as CK_MECHANISM_PTR,
                base_key.handle(),
                template.as_mut_ptr(),
                template.len().try_into()?,
                &mut handle,
            ))
            .into_result()?;
        }

        Ok(ObjectHandle::new(handle))
    }

    /// Wrap key
    pub fn wrap_key(
        &self,
        mechanism: &Mechanism,
        wrapping_key: ObjectHandle,
        key: ObjectHandle,
    ) -> Result<Vec<u8>> {
        let mut mechanism: CK_MECHANISM = mechanism.into();
        unsafe {
            let mut wrapped_key_len = 0;

            Rv::from(get_pkcs11!(self.client(), C_WrapKey)(
                self.handle(),
                &mut mechanism as CK_MECHANISM_PTR,
                wrapping_key.handle(),
                key.handle(),
                std::ptr::null_mut(),
                &mut wrapped_key_len,
            ))
            .into_result()?;

            let mut wrapped_key = vec![0; wrapped_key_len.try_into()?];

            Rv::from(get_pkcs11!(self.client(), C_WrapKey)(
                self.handle(),
                &mut mechanism as CK_MECHANISM_PTR,
                wrapping_key.handle(),
                key.handle(),
                wrapped_key.as_mut_ptr(),
                &mut wrapped_key_len,
            ))
            .into_result()?;

            Ok(wrapped_key)
        }
    }

    /// Unwrap previously wrapped key
    pub fn unwrap_key(
        &self,
        mechanism: &Mechanism,
        unwrapping_key: ObjectHandle,
        wrapped_key: &[u8],
        template: &[Attribute],
    ) -> Result<ObjectHandle> {
        let mut mechanism: CK_MECHANISM = mechanism.into();
        let mut template: Vec<CK_ATTRIBUTE> = template.iter().map(|attr| attr.into()).collect();
        let mut handle = 0;
        unsafe {
            Rv::from(get_pkcs11!(self.client(), C_UnwrapKey)(
                self.handle(),
                &mut mechanism as CK_MECHANISM_PTR,
                unwrapping_key.handle(),
                wrapped_key.as_ptr() as *mut u8,
                wrapped_key.len().try_into()?,
                template.as_mut_ptr(),
                template.len().try_into()?,
                &mut handle,
            ))
            .into_result()?;
        }

        Ok(ObjectHandle::new(handle))
    }
}