nss/
ecdh.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 crate::{
6    ec::{PrivateKey, PublicKey},
7    error::*,
8    pk11::types::SymKey,
9    util::{assert_nss_initialized, map_nss_secstatus, sec_item_as_slice, ScopedPtr},
10};
11
12pub fn ecdh_agreement(priv_key: &PrivateKey, pub_key: &PublicKey) -> Result<Vec<u8>> {
13    assert_nss_initialized();
14    if priv_key.curve() != pub_key.curve() {
15        return Err(ErrorKind::InternalError.into());
16    }
17    // The following code is adapted from:
18    // https://searchfox.org/mozilla-central/rev/444ee13e14fe30451651c0f62b3979c76766ada4/dom/crypto/WebCryptoTask.cpp#2835
19
20    // CKM_SHA512_HMAC and CKA_SIGN are key type and usage attributes of the
21    // derived symmetric key and don't matter because we ignore them anyway.
22    let sym_key = unsafe {
23        SymKey::from_ptr(nss_sys::PK11_PubDeriveWithKDF(
24            priv_key.as_mut_ptr(),
25            pub_key.as_mut_ptr(),
26            nss_sys::PR_FALSE,
27            std::ptr::null_mut(),
28            std::ptr::null_mut(),
29            nss_sys::CKM_ECDH1_DERIVE.into(),
30            nss_sys::CKM_SHA512_HMAC.into(),
31            nss_sys::CKA_SIGN.into(),
32            0,
33            nss_sys::CKD_NULL.into(),
34            std::ptr::null_mut(),
35            std::ptr::null_mut(),
36        ))?
37    };
38
39    map_nss_secstatus(|| unsafe { nss_sys::PK11_ExtractKeyValue(sym_key.as_mut_ptr()) })?;
40
41    // This doesn't leak, because the SECItem* returned by PK11_GetKeyData
42    // just refers to a buffer managed by `sym_key` which we copy into `buf`.
43    let mut key_data = unsafe { *nss_sys::PK11_GetKeyData(sym_key.as_mut_ptr()) };
44    let buf = unsafe { sec_item_as_slice(&mut key_data)? };
45    Ok(buf.to_vec())
46}