Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for EVP_PKEY_derive_set_peer_ex in OpenSSL 3 #1956

Merged
merged 5 commits into from Jun 7, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions openssl-sys/src/handwritten/evp.rs
Expand Up @@ -522,6 +522,12 @@ extern "C" {

pub fn EVP_PKEY_derive_init(ctx: *mut EVP_PKEY_CTX) -> c_int;
pub fn EVP_PKEY_derive_set_peer(ctx: *mut EVP_PKEY_CTX, peer: *mut EVP_PKEY) -> c_int;
#[cfg(ossl300)]
pub fn EVP_PKEY_derive_set_peer_ex(
ctx: *mut EVP_PKEY_CTX,
peer: *mut EVP_PKEY,
validate_peer: c_int,
) -> c_int;
pub fn EVP_PKEY_derive(ctx: *mut EVP_PKEY_CTX, key: *mut c_uchar, size: *mut size_t) -> c_int;

#[cfg(ossl300)]
Expand Down
37 changes: 37 additions & 0 deletions openssl/src/derive.rs
Expand Up @@ -93,6 +93,29 @@ impl<'a> Deriver<'a> {
unsafe { cvt(ffi::EVP_PKEY_derive_set_peer(self.0, key.as_ptr())).map(|_| ()) }
}

/// Sets the peer key used for secret derivation along with optionally validating the peer public key.
///
/// Requires OpenSSL 3.0.0 or newer.
#[corresponds(EVP_PKEY_derive_set_peer_ex)]
#[cfg(ossl300)]
pub fn set_peer_ex<T>(
&mut self,
key: &'a PKeyRef<T>,
validate_peer: bool,
) -> Result<(), ErrorStack>
where
T: HasPublic,
{
unsafe {
cvt(ffi::EVP_PKEY_derive_set_peer_ex(
self.0,
key.as_ptr(),
validate_peer as i32,
))
.map(|_| ())
}
}

/// Returns the size of the shared secret.
///
/// It can be used to size the buffer passed to [`Deriver::derive`].
Expand Down Expand Up @@ -179,4 +202,18 @@ mod test {
let shared = deriver.derive_to_vec().unwrap();
assert!(!shared.is_empty());
}

#[test]
#[cfg(ossl300)]
fn test_ec_key_derive_ex() {
let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
let ec_key = EcKey::generate(&group).unwrap();
let ec_key2 = EcKey::generate(&group).unwrap();
let pkey = PKey::from_ec_key(ec_key).unwrap();
let pkey2 = PKey::from_ec_key(ec_key2).unwrap();
let mut deriver = Deriver::new(&pkey).unwrap();
deriver.set_peer_ex(&pkey2, true).unwrap();
let shared = deriver.derive_to_vec().unwrap();
assert!(!shared.is_empty());
}
}