libcryptsetup_rs/
key.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5use std::{
6    os::raw::{c_int, c_uint},
7    ptr,
8};
9
10use crate::{device::CryptDevice, err::LibcryptErr};
11
12/// Handle for volume key operations
13pub struct CryptVolumeKeyHandle<'a> {
14    reference: &'a mut CryptDevice,
15}
16
17impl<'a> CryptVolumeKeyHandle<'a> {
18    pub(crate) fn new(reference: &'a mut CryptDevice) -> Self {
19        CryptVolumeKeyHandle { reference }
20    }
21
22    /// Get volume key from crypt device - first tuple element is key slot, second is volume key
23    /// size
24    pub fn get(
25        &mut self,
26        keyslot: Option<c_uint>,
27        volume_key: &mut [u8],
28        passphrase: Option<&[u8]>,
29    ) -> Result<(c_int, crate::size_t), LibcryptErr> {
30        let mut volume_key_size_t = volume_key.len();
31        errno_int_success!(mutex!(libcryptsetup_rs_sys::crypt_volume_key_get(
32            self.reference.as_ptr(),
33            keyslot
34                .map(|i| i as c_int)
35                .unwrap_or(libcryptsetup_rs_sys::CRYPT_ANY_SLOT),
36            to_mut_byte_ptr!(volume_key),
37            &mut volume_key_size_t as *mut _,
38            passphrase
39                .as_ref()
40                .map(|s| to_byte_ptr!(s))
41                .unwrap_or(ptr::null()),
42            passphrase.map(|p| p.len()).unwrap_or(0),
43        )))
44        .map(|i| (i, volume_key_size_t))
45    }
46
47    /// Verify that volume key is valid for crypt device
48    pub fn verify(&mut self, volume_key: &[u8]) -> Result<(), LibcryptErr> {
49        errno!(mutex!(libcryptsetup_rs_sys::crypt_volume_key_verify(
50            self.reference.as_ptr(),
51            to_byte_ptr!(volume_key),
52            volume_key.len(),
53        )))
54    }
55}