| 1 |
use crate::algorithms::{AeadAlgorithm, HpkeAlgorithm, KdfAlgorithm, KemAlgorithm}; |
| 2 |
#[cfg(any(test, feature = "test-utils"))] |
| 3 |
use crate::crypto::PrivateKey; |
| 4 |
use crate::crypto::secret_box::SecretBox; |
| 5 |
use crate::crypto::{Error, PrivateKeyOps, PublicKeyOps}; |
| 6 |
use bssl_crypto::{hkdf, hpke, x25519}; |
| 7 |
|
| 8 |
/// X25519-based public key implementation. |
| 9 |
#[derive(Debug, Clone, PartialEq, Eq)] |
| 10 |
pub struct X25519PublicKey(pub(crate) [u8; 32]); |
| 11 |
|
| 12 |
impl AsRef<[u8]> for X25519PublicKey { |
| 13 |
fn as_ref(&self) -> &[u8] { |
| 14 |
&self.0 |
| 15 |
} |
| 16 |
} |
| 17 |
|
| 18 |
impl PublicKeyOps for X25519PublicKey { |
| 19 |
fn hpke_seal_internal( |
| 20 |
&self, |
| 21 |
plaintext: &SecretBox, |
| 22 |
aad: &[u8], |
| 23 |
algo: &HpkeAlgorithm, |
| 24 |
) -> Result<(Vec<u8>, Vec<u8>), Error> { |
| 25 |
let ( |
| 26 |
Ok(KemAlgorithm::DhkemX25519HkdfSha256), |
| 27 |
Ok(KdfAlgorithm::HkdfSha256), |
| 28 |
Ok(AeadAlgorithm::Aes256Gcm), |
| 29 |
) = ( |
| 30 |
KemAlgorithm::try_from(algo.kem), |
| 31 |
KdfAlgorithm::try_from(algo.kdf), |
| 32 |
AeadAlgorithm::try_from(algo.aead), |
| 33 |
) |
| 34 |
else { |
| 35 |
return Err(Error::UnsupportedAlgorithm); |
| 36 |
}; |
| 37 |
|
| 38 |
let params = hpke::Params::new( |
| 39 |
hpke::Kem::X25519HkdfSha256, |
| 40 |
hpke::Kdf::HkdfSha256, |
| 41 |
hpke::Aead::Aes256Gcm, |
| 42 |
); |
| 43 |
|
| 44 |
let (mut sender_ctx, encapsulated_key) = |
| 45 |
hpke::SenderContext::new(¶ms, self.as_ref(), b"") |
| 46 |
.ok_or(Error::HpkeEncryptionError)?; |
| 47 |
|
| 48 |
let ciphertext = sender_ctx.seal(plaintext.as_slice(), aad); |
| 49 |
Ok((encapsulated_key, ciphertext)) |
| 50 |
} |
| 51 |
|
| 52 |
#[cfg(any(test, feature = "test-utils"))] |
| 53 |
fn encap_internal( |
| 54 |
&self, |
| 55 |
ephemeral_sk: Option<&PrivateKey>, |
| 56 |
) -> Result<(SecretBox, Vec<u8>), Error> { |
| 57 |
let (pk_e_bytes, sk_e_bytes) = match ephemeral_sk { |
| 58 |
Some(PrivateKey::X25519(sk)) => { |
| 59 |
let sk_e = x25519::PrivateKey( |
| 60 |
sk.0.as_slice() |
| 61 |
.try_into() |
| 62 |
.map_err(|_| Error::KeyLenMismatch)?, |
| 63 |
); |
| 64 |
(sk_e.to_public().to_vec(), sk.0.as_slice().to_vec()) |
| 65 |
} |
| 66 |
None => hpke::Kem::X25519HkdfSha256.generate_keypair(), |
| 67 |
}; |
| 68 |
|
| 69 |
let sk_e = x25519::PrivateKey(sk_e_bytes.try_into().map_err(|_| Error::CryptoError)?); |
| 70 |
let pk_r = self.0; |
| 71 |
|
| 72 |
// 1. Compute Diffie-Hellman shared secret |
| 73 |
// dh = dhExchange(skE, pkR) |
| 74 |
let shared_key = SecretBox::new( |
| 75 |
sk_e.compute_shared_key(&pk_r) |
| 76 |
.ok_or(Error::CryptoError)? |
| 77 |
.to_vec(), |
| 78 |
); |
| 79 |
|
| 80 |
// DHKEM(X25519, HKDF-SHA256) |
| 81 |
// suite_id = "KEM" || I2OSP(kem_id, 2) |
| 82 |
// For X25519 (0x0020) |
| 83 |
let suite_id = [b'K', b'E', b'M', 0, 0x20]; |
| 84 |
|
| 85 |
// 2. Extract eae_prk |
| 86 |
// eae_prk = LabeledExtract("", "eae_prk", dh) |
| 87 |
let prk = labeled_extract(b"", b"eae_prk", shared_key.as_slice(), &suite_id); |
| 88 |
|
| 89 |
// 3. Expand shared_secret |
| 90 |
// shared_secret = LabeledExpand(eae_prk, "shared_secret", enc || pkR, L) |
| 91 |
let info = [&pk_e_bytes[..], &pk_r[..]].concat(); |
| 92 |
|
| 93 |
let shared_secret = labeled_expand(&prk, b"shared_secret", &info, &suite_id, 32)?; |
| 94 |
|
| 95 |
Ok((shared_secret, pk_e_bytes.to_vec())) |
| 96 |
} |
| 97 |
|
| 98 |
fn as_bytes(&self) -> &[u8] { |
| 99 |
&self.0 |
| 100 |
} |
| 101 |
} |
| 102 |
|
| 103 |
/// X25519-based private key implementation. |
| 104 |
pub struct X25519PrivateKey(pub(crate) SecretBox); |
| 105 |
|
| 106 |
impl From<X25519PrivateKey> for SecretBox { |
| 107 |
fn from(key: X25519PrivateKey) -> SecretBox { |
| 108 |
key.0 |
| 109 |
} |
| 110 |
} |
| 111 |
|
| 112 |
impl PrivateKeyOps for X25519PrivateKey { |
| 113 |
/// Decapsulates the shared secret from an encapsulated key. |
| 114 |
/// Follows RFC 9180 Section 4.1. DHKEM(Group, Hash). |
| 115 |
fn decaps_internal(&self, enc: &[u8]) -> Result<SecretBox, Error> { |
| 116 |
let priv_key = x25519::PrivateKey( |
| 117 |
self.0 |
| 118 |
.as_slice() |
| 119 |
.try_into() |
| 120 |
.map_err(|_| Error::KeyLenMismatch)?, |
| 121 |
); |
| 122 |
|
| 123 |
// 1. Compute Diffie-Hellman shared secret |
| 124 |
// dh = dhExchange(skR, pkE) |
| 125 |
let shared_key = SecretBox::new( |
| 126 |
priv_key |
| 127 |
.compute_shared_key(enc.try_into().map_err(|_| Error::KeyLenMismatch)?) |
| 128 |
.ok_or(Error::DecapsError)? |
| 129 |
.to_vec(), |
| 130 |
); |
| 131 |
|
| 132 |
// DHKEM(X25519, HKDF-SHA256) |
| 133 |
// suite_id = "KEM" || I2OSP(kem_id, 2) |
| 134 |
// For X25519 (0x0020) |
| 135 |
let suite_id = [b'K', b'E', b'M', 0, 0x20]; |
| 136 |
|
| 137 |
// 2. Extract eae_prk |
| 138 |
// eae_prk = LabeledExtract("", "eae_prk", dh) |
| 139 |
let prk = labeled_extract(b"", b"eae_prk", shared_key.as_slice(), &suite_id); |
| 140 |
|
| 141 |
let pub_key = priv_key.to_public(); |
| 142 |
|
| 143 |
// 3. Expand shared_secret |
| 144 |
// shared_secret = LabeledExpand(eae_prk, "shared_secret", enc || pkR, L) |
| 145 |
let info = [enc, &pub_key].concat(); |
| 146 |
|
| 147 |
labeled_expand(&prk, b"shared_secret", &info, &suite_id, 32) |
| 148 |
} |
| 149 |
|
| 150 |
fn hpke_open_internal( |
| 151 |
&self, |
| 152 |
enc: &[u8], |
| 153 |
ciphertext: &[u8], |
| 154 |
aad: &[u8], |
| 155 |
algo: &HpkeAlgorithm, |
| 156 |
) -> Result<SecretBox, Error> { |
| 157 |
let ( |
| 158 |
Ok(KemAlgorithm::DhkemX25519HkdfSha256), |
| 159 |
Ok(KdfAlgorithm::HkdfSha256), |
| 160 |
Ok(AeadAlgorithm::Aes256Gcm), |
| 161 |
) = ( |
| 162 |
KemAlgorithm::try_from(algo.kem), |
| 163 |
KdfAlgorithm::try_from(algo.kdf), |
| 164 |
AeadAlgorithm::try_from(algo.aead), |
| 165 |
) |
| 166 |
else { |
| 167 |
return Err(Error::UnsupportedAlgorithm); |
| 168 |
}; |
| 169 |
|
| 170 |
let params = hpke::Params::new( |
| 171 |
hpke::Kem::X25519HkdfSha256, |
| 172 |
hpke::Kdf::HkdfSha256, |
| 173 |
hpke::Aead::Aes256Gcm, |
| 174 |
); |
| 175 |
|
| 176 |
let mut recipient_ctx = hpke::RecipientContext::new(¶ms, self.0.as_slice(), enc, b"") |
| 177 |
.ok_or(Error::HpkeDecryptionError)?; |
| 178 |
|
| 179 |
recipient_ctx |
| 180 |
.open(ciphertext, aad) |
| 181 |
.map(SecretBox::new) |
| 182 |
.ok_or(Error::HpkeDecryptionError) |
| 183 |
} |
| 184 |
} |
| 185 |
|
| 186 |
/// LabeledExtract(salt, label, ikm) = HKDF-Extract(salt, "HPKE-v1" || suite_id || label || ikm) |
| 187 |
fn labeled_extract(salt: &[u8], label: &[u8], ikm: &[u8], suite_id: &[u8]) -> hkdf::Prk { |
| 188 |
// print the params received |
| 189 |
println!( |
| 190 |
"labeled_extract: salt={:?}, label={:?}, ikm={:?}, suite_id={:?}", |
| 191 |
salt, label, ikm, suite_id |
| 192 |
); |
| 193 |
|
| 194 |
let labeled_ikm = SecretBox::new([b"HPKE-v1".as_slice(), suite_id, label, ikm].concat()); |
| 195 |
hkdf::HkdfSha256::extract(labeled_ikm.as_slice(), hkdf::Salt::None) |
| 196 |
} |
| 197 |
|
| 198 |
/// LabeledExpand(prk, label, info, L) = HKDF-Expand(prk, "HPKE-v1" || suite_id || label || info, L) |
| 199 |
fn labeled_expand( |
| 200 |
prk: &hkdf::Prk, |
| 201 |
label: &[u8], |
| 202 |
info: &[u8], |
| 203 |
suite_id: &[u8], |
| 204 |
len: u16, |
| 205 |
) -> Result<SecretBox, Error> { |
| 206 |
let labeled_info = |
| 207 |
SecretBox::new([&len.to_be_bytes()[..], b"HPKE-v1", suite_id, label, info].concat()); |
| 208 |
|
| 209 |
let mut result = vec![0u8; len as usize]; |
| 210 |
prk.expand_into(labeled_info.as_slice(), &mut result) |
| 211 |
.map_err(|_| Error::DecapsError)?; |
| 212 |
|
| 213 |
Ok(SecretBox::new(result)) |
| 214 |
} |
| 215 |
|
| 216 |
/// Generates a new X25519 keypair. |
| 217 |
pub(crate) fn generate_keypair() -> (X25519PublicKey, X25519PrivateKey) { |
| 218 |
let (pk, sk) = hpke::Kem::X25519HkdfSha256.generate_keypair(); |
| 219 |
( |
| 220 |
X25519PublicKey(pk.try_into().expect("X25519 public key must be 32 bytes")), |
| 221 |
X25519PrivateKey(SecretBox::new(sk)), |
| 222 |
) |
| 223 |
} |
| 224 |
|
| 225 |
#[cfg(test)] |
| 226 |
mod tests { |
| 227 |
use super::*; |
| 228 |
use hex; |
| 229 |
|
| 230 |
#[test] |
| 231 |
fn test_decaps_x25519_clamped_vector() { |
| 232 |
// Vectors from https://www.rfc-editor.org/rfc/rfc9180.html#appendix-A.1 |
| 233 |
let sk_r_hex = "4612c550263fc8ad58375df3f557aac531d26850903e55a9f23f21d8534e8ac8"; |
| 234 |
let enc_hex = "37fda3567bdbd628e88668c3c8d7e97d1d1253b6d4ea6d44c150f741f1bf4431"; |
| 235 |
|
| 236 |
let expected_shared_secret_hex = |
| 237 |
"fe0e18c9f024ce43799ae393c7e8fe8fce9d218875e8227b0187c04e7d2ea1fc"; |
| 238 |
|
| 239 |
let sk_r_bytes: Vec<u8> = hex::decode(sk_r_hex).unwrap(); |
| 240 |
let sk_r = X25519PrivateKey(SecretBox::new(sk_r_bytes)); |
| 241 |
let enc = hex::decode(enc_hex).unwrap(); |
| 242 |
|
| 243 |
let result = sk_r.decaps_internal(&enc).expect("Decapsulation failed"); |
| 244 |
|
| 245 |
assert_eq!( |
| 246 |
hex::encode(result.as_slice()), |
| 247 |
expected_shared_secret_hex, |
| 248 |
"Shared secret mismatch" |
| 249 |
); |
| 250 |
} |
| 251 |
|
| 252 |
#[test] |
| 253 |
fn test_labeled_extract_and_expand() { |
| 254 |
let suite_id = [b'K', b'E', b'M', 0, 0x20]; |
| 255 |
let salt = b"test_salt"; |
| 256 |
let label = b"test_label"; |
| 257 |
let ikm = b"test_ikm"; |
| 258 |
let info = b"test_info"; |
| 259 |
|
| 260 |
// Test labeled_extract |
| 261 |
let prk = labeled_extract(salt, label, ikm, &suite_id); |
| 262 |
|
| 263 |
// Test labeled_expand with length 32 |
| 264 |
let len = 32; |
| 265 |
let result = labeled_expand(&prk, label, info, &suite_id, len).expect("expand failed"); |
| 266 |
assert_eq!(result.as_slice().len(), len as usize); |
| 267 |
|
| 268 |
// Test labeled_expand with different info produces different result |
| 269 |
let result2 = |
| 270 |
labeled_expand(&prk, label, b"other_info", &suite_id, len).expect("expand failed"); |
| 271 |
assert_ne!(result.as_slice(), result2.as_slice()); |
| 272 |
|
| 273 |
// Test labeled_expand with different label produces different result |
| 274 |
let result3 = |
| 275 |
labeled_expand(&prk, b"other_label", info, &suite_id, len).expect("expand failed"); |
| 276 |
assert_ne!(result.as_slice(), result3.as_slice()); |
| 277 |
} |
| 278 |
|
| 279 |
#[test] |
| 280 |
fn test_encaps_x25519_clamped_vector() { |
| 281 |
// Vectors from https://www.rfc-editor.org/rfc/rfc9180.html#appendix-A.1 |
| 282 |
let sk_e_hex = "52c4a758a802cd8b936eceea314432798d5baf2d7e9235dc084ab1b9cfa2f736"; |
| 283 |
let pk_e_hex = "37fda3567bdbd628e88668c3c8d7e97d1d1253b6d4ea6d44c150f741f1bf4431"; |
| 284 |
let pk_r_hex = "3948cfe0ad1ddb695d780e59077195da6c56506b027329794ab02bca80815c4d"; |
| 285 |
let expected_shared_secret_hex = |
| 286 |
"fe0e18c9f024ce43799ae393c7e8fe8fce9d218875e8227b0187c04e7d2ea1fc"; |
| 287 |
|
| 288 |
let sk_e_bytes: Vec<u8> = hex::decode(sk_e_hex).unwrap(); |
| 289 |
let pk_r_bytes: [u8; 32] = hex::decode(pk_r_hex).unwrap().try_into().unwrap(); |
| 290 |
|
| 291 |
let pk_r = X25519PublicKey(pk_r_bytes); |
| 292 |
let sk_e = PrivateKey::X25519(X25519PrivateKey(SecretBox::new(sk_e_bytes))); |
| 293 |
|
| 294 |
let (shared_secret, enc) = pk_r.encap_internal(Some(&sk_e)).expect("encap failed"); |
| 295 |
|
| 296 |
assert_eq!(hex::encode(enc), pk_e_hex, "Encapsulated key mismatch"); |
| 297 |
assert_eq!( |
| 298 |
hex::encode(shared_secret.as_slice()), |
| 299 |
expected_shared_secret_hex, |
| 300 |
"Shared secret mismatch" |
| 301 |
); |
| 302 |
} |
| 303 |
} |