fix(identity): correctly follow extract-expand for HKDF

As @mxinden pointed out in https://github.com/libp2p/rust-libp2p/pull/4554#discussion_r1344747938, we were not correctly following the HKDF steps of extract and expand.

Pull-Request: #4589.
This commit is contained in:
Thomas Eizinger
2023-10-09 12:31:10 +11:00
committed by GitHub
parent ef9c544d4d
commit 77149f08c4
6 changed files with 31 additions and 15 deletions

2
Cargo.lock generated
View File

@@ -2634,7 +2634,7 @@ dependencies = [
[[package]]
name = "libp2p-identity"
version = "0.2.4"
version = "0.2.5"
dependencies = [
"asn1_der",
"base64 0.21.4",

View File

@@ -82,7 +82,7 @@ libp2p-dns = { version = "0.40.1", path = "transports/dns" }
libp2p-floodsub = { version = "0.43.0", path = "protocols/floodsub" }
libp2p-gossipsub = { version = "0.45.1", path = "protocols/gossipsub" }
libp2p-identify = { version = "0.43.1", path = "protocols/identify" }
libp2p-identity = { version = "0.2.4" }
libp2p-identity = { version = "0.2.5" }
libp2p-kad = { version = "0.44.6", path = "protocols/kad" }
libp2p-mdns = { version = "0.44.0", path = "protocols/mdns" }
libp2p-memory-connection-limits = { version = "0.1.0", path = "misc/memory-connection-limits" }

View File

@@ -1,3 +1,8 @@
## 0.2.5
- Fix usage of HKDF within `Keypair::derive_secret`.
See [PR 4554](https://github.com/libp2p/rust-libp2p/pull/4554).
## 0.2.4
- Implement `Keypair::derive_secret`, to deterministically derive a new secret from the embedded secret key.

View File

@@ -1,6 +1,6 @@
[package]
name = "libp2p-identity"
version = "0.2.4"
version = "0.2.5"
edition = "2021"
description = "Data structures and algorithms for identifying peers in libp2p."
rust-version = { workspace = true }

View File

@@ -358,20 +358,30 @@ impl Keypair {
/// let new_key = key.derive_secret(b"my encryption key").expect("can derive secret for ed25519");
/// # }
/// ```
#[allow(unused_variables, unreachable_code)]
///
#[cfg(any(
feature = "ecdsa",
feature = "secp256k1",
feature = "ed25519",
feature = "rsa"
))]
pub fn derive_secret(&self, domain: &[u8]) -> Option<[u8; 32]> {
#[cfg(any(
feature = "ecdsa",
feature = "secp256k1",
feature = "ed25519",
feature = "rsa"
))]
return Some(
hkdf::Hkdf::<sha2::Sha256>::extract(None, &[domain, &self.secret()?].concat())
.0
.into(),
);
let mut okm = [0u8; 32];
hkdf::Hkdf::<sha2::Sha256>::new(None, &self.secret()?)
.expand(domain, &mut okm)
.expect("okm.len() == 32");
Some(okm)
}
// We build docs with all features so this doesn't need to have any docs.
#[cfg(not(any(
feature = "ecdsa",
feature = "secp256k1",
feature = "ed25519",
feature = "rsa"
)))]
pub fn derive_secret(&self, _: &[u8]) -> Option<[u8; 32]> {
None
}

View File

@@ -10,4 +10,5 @@ fn using_keypair(kp: Keypair) {
let _ = kp.to_protobuf_encoding();
let _ = kp.sign(&[]);
let _ = kp.public();
let _: Option<[u8; 32]> = kp.derive_secret(b"foobar");
}