| 1 |
use crate::algorithms::{HpkeAlgorithm, KemAlgorithm}; |
| 2 |
pub mod secret_box; |
| 3 |
use crate::crypto::secret_box::SecretBox; |
| 4 |
use clear_on_drop::clear_stack_on_return; |
| 5 |
use thiserror::Error; |
| 6 |
|
| 7 |
mod x25519; |
| 8 |
pub use x25519::{X25519PrivateKey, X25519PublicKey}; |
| 9 |
|
| 10 |
const CLEAR_STACK_PAGES: usize = 2; |
| 11 |
|
| 12 |
/// A trait for public keys with algorithm-specific implementations. |
| 13 |
pub(crate) trait PublicKeyOps: Send + Sync { |
| 14 |
/// Encrypts a plaintext using HPKE. |
| 15 |
/// |
| 16 |
/// Returns a tuple containing the encapsulated key and the ciphertext respectively. |
| 17 |
fn hpke_seal_internal( |
| 18 |
&self, |
| 19 |
plaintext: &SecretBox, |
| 20 |
aad: &[u8], |
| 21 |
algo: &HpkeAlgorithm, |
| 22 |
) -> Result<(Vec<u8>, Vec<u8>), Error>; |
| 23 |
|
| 24 |
#[cfg(any(test, feature = "test-utils"))] |
| 25 |
/// Performs DHKEM encapsulation operation. |
| 26 |
/// |
| 27 |
/// Returns a tuple containing the shared secret as a `SecretBox` and the encapsulated key respectively. |
| 28 |
/// |
| 29 |
/// If `ephemeral_sk` is provided, it is used as the ephemeral private key. |
| 30 |
/// Otherwise, a random ephemeral key is generated. |
| 31 |
fn encap_internal( |
| 32 |
&self, |
| 33 |
ephemeral_sk: Option<&PrivateKey>, |
| 34 |
) -> Result<(SecretBox, Vec<u8>), Error>; |
| 35 |
|
| 36 |
/// Returns the raw bytes of the public key. |
| 37 |
fn as_bytes(&self) -> &[u8]; |
| 38 |
} |
| 39 |
|
| 40 |
/// A trait for private keys with algorithm-specific implementations. |
| 41 |
pub(crate) trait PrivateKeyOps: Send + Sync { |
| 42 |
/// Decapsulates the shared secret from an encapsulated key. |
| 43 |
/// |
| 44 |
/// Returns the decapsulated shared secret as a `SecretBox`. |
| 45 |
fn decaps_internal(&self, enc: &[u8]) -> Result<SecretBox, Error>; |
| 46 |
|
| 47 |
/// Decrypts a ciphertext using HPKE. |
| 48 |
/// |
| 49 |
/// Returns the decrypted plaintext as a `SecretBox`. |
| 50 |
fn hpke_open_internal( |
| 51 |
&self, |
| 52 |
enc: &[u8], |
| 53 |
ciphertext: &[u8], |
| 54 |
aad: &[u8], |
| 55 |
algo: &HpkeAlgorithm, |
| 56 |
) -> Result<SecretBox, Error>; |
| 57 |
} |
| 58 |
|
| 59 |
/// A wrapper enum for different public key types. |
| 60 |
#[derive(Debug, Clone, PartialEq, Eq)] |
| 61 |
pub enum PublicKey { |
| 62 |
X25519(X25519PublicKey), |
| 63 |
} |
| 64 |
|
| 65 |
impl PublicKey { |
| 66 |
/// Returns the raw bytes of the public key. |
| 67 |
pub fn as_bytes(&self) -> &[u8] { |
| 68 |
match self { |
| 69 |
PublicKey::X25519(pk) => pk.as_bytes(), |
| 70 |
} |
| 71 |
} |
| 72 |
} |
| 73 |
|
| 74 |
impl TryFrom<Vec<u8>> for PublicKey { |
| 75 |
type Error = Error; |
| 76 |
|
| 77 |
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> { |
| 78 |
let bytes: [u8; 32] = value.try_into().map_err(|_| Error::KeyLenMismatch)?; |
| 79 |
Ok(PublicKey::X25519(X25519PublicKey(bytes))) |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
impl PublicKeyOps for PublicKey { |
| 84 |
fn hpke_seal_internal( |
| 85 |
&self, |
| 86 |
plaintext: &SecretBox, |
| 87 |
aad: &[u8], |
| 88 |
algo: &HpkeAlgorithm, |
| 89 |
) -> Result<(Vec<u8>, Vec<u8>), Error> { |
| 90 |
match self { |
| 91 |
PublicKey::X25519(pk) => pk.hpke_seal_internal(plaintext, aad, algo), |
| 92 |
} |
| 93 |
} |
| 94 |
|
| 95 |
#[cfg(any(test, feature = "test-utils"))] |
| 96 |
fn encap_internal( |
| 97 |
&self, |
| 98 |
ephemeral_sk: Option<&PrivateKey>, |
| 99 |
) -> Result<(SecretBox, Vec<u8>), Error> { |
| 100 |
match self { |
| 101 |
PublicKey::X25519(pk) => pk.encap_internal(ephemeral_sk), |
| 102 |
} |
| 103 |
} |
| 104 |
|
| 105 |
fn as_bytes(&self) -> &[u8] { |
| 106 |
self.as_bytes() |
| 107 |
} |
| 108 |
} |
| 109 |
|
| 110 |
/// A wrapper enum for different private key types. |
| 111 |
pub enum PrivateKey { |
| 112 |
X25519(X25519PrivateKey), |
| 113 |
} |
| 114 |
|
| 115 |
impl From<SecretBox> for PrivateKey { |
| 116 |
fn from(secret: SecretBox) -> Self { |
| 117 |
PrivateKey::X25519(X25519PrivateKey(secret)) |
| 118 |
} |
| 119 |
} |
| 120 |
|
| 121 |
impl From<PrivateKey> for SecretBox { |
| 122 |
fn from(key: PrivateKey) -> SecretBox { |
| 123 |
match key { |
| 124 |
PrivateKey::X25519(sk) => SecretBox::from(sk), |
| 125 |
} |
| 126 |
} |
| 127 |
} |
| 128 |
|
| 129 |
impl PrivateKeyOps for PrivateKey { |
| 130 |
fn decaps_internal(&self, enc: &[u8]) -> Result<SecretBox, Error> { |
| 131 |
match self { |
| 132 |
PrivateKey::X25519(sk) => sk.decaps_internal(enc), |
| 133 |
} |
| 134 |
} |
| 135 |
|
| 136 |
fn hpke_open_internal( |
| 137 |
&self, |
| 138 |
enc: &[u8], |
| 139 |
ciphertext: &[u8], |
| 140 |
aad: &[u8], |
| 141 |
algo: &HpkeAlgorithm, |
| 142 |
) -> Result<SecretBox, Error> { |
| 143 |
match self { |
| 144 |
PrivateKey::X25519(sk) => sk.hpke_open_internal(enc, ciphertext, aad, algo), |
| 145 |
} |
| 146 |
} |
| 147 |
} |
| 148 |
|
| 149 |
#[derive(Debug, Error)] |
| 150 |
pub enum Error { |
| 151 |
#[error("Key length mismatch")] |
| 152 |
KeyLenMismatch, |
| 153 |
#[error("Decapsulation error")] |
| 154 |
DecapsError, |
| 155 |
#[error("HPKE decryption error")] |
| 156 |
HpkeDecryptionError, |
| 157 |
#[error("HPKE encryption error")] |
| 158 |
HpkeEncryptionError, |
| 159 |
#[error("Unsupported algorithm")] |
| 160 |
UnsupportedAlgorithm, |
| 161 |
#[error("Invalid key")] |
| 162 |
InvalidKey, |
| 163 |
#[error("Crypto library error")] |
| 164 |
CryptoError, |
| 165 |
} |
| 166 |
|
| 167 |
/// Generates a keypair for the given KEM algorithm. |
| 168 |
/// |
| 169 |
/// Returns a tuple containing the public and private keys respectively. |
| 170 |
pub fn generate_keypair(algo: KemAlgorithm) -> Result<(PublicKey, PrivateKey), Error> { |
| 171 |
clear_stack_on_return(CLEAR_STACK_PAGES, || match algo { |
| 172 |
KemAlgorithm::DhkemX25519HkdfSha256 => { |
| 173 |
let (pk, sk) = x25519::generate_keypair(); |
| 174 |
Ok((PublicKey::X25519(pk), PrivateKey::X25519(sk))) |
| 175 |
} |
| 176 |
_ => Err(Error::UnsupportedAlgorithm), |
| 177 |
}) |
| 178 |
} |
| 179 |
|
| 180 |
/// Encapsulates the shared secret using the specified public key. |
| 181 |
/// |
| 182 |
/// Returns the shared secret as a `SecretBox` and the encapsulated key respectively. |
| 183 |
#[cfg(any(test, feature = "test-utils"))] |
| 184 |
pub fn encap(pub_key: &PublicKey) -> Result<(SecretBox, Vec<u8>), Error> { |
| 185 |
clear_stack_on_return(CLEAR_STACK_PAGES, || pub_key.encap_internal(None)) |
| 186 |
} |
| 187 |
|
| 188 |
/// Decapsulates the shared secret from an encapsulated key using the specified private key. |
| 189 |
/// |
| 190 |
/// Returns the decapsulated shared secret as a `SecretBox`. |
| 191 |
pub fn decaps(priv_key: &PrivateKey, enc: &[u8]) -> Result<SecretBox, Error> { |
| 192 |
clear_stack_on_return(CLEAR_STACK_PAGES, || priv_key.decaps_internal(enc)) |
| 193 |
} |
| 194 |
|
| 195 |
/// Decrypts a ciphertext using HPKE (Hybrid Public Key Encryption). |
| 196 |
/// |
| 197 |
/// Returns the decrypted plaintext as a `SecretBox`. |
| 198 |
pub fn hpke_open( |
| 199 |
priv_key: &PrivateKey, |
| 200 |
enc: &[u8], |
| 201 |
ciphertext: &[u8], |
| 202 |
aad: &[u8], |
| 203 |
algo: &HpkeAlgorithm, |
| 204 |
) -> Result<SecretBox, Error> { |
| 205 |
clear_stack_on_return(CLEAR_STACK_PAGES, || { |
| 206 |
priv_key.hpke_open_internal(enc, ciphertext, aad, algo) |
| 207 |
}) |
| 208 |
} |
| 209 |
|
| 210 |
/// Encrypts a plaintext using HPKE (Hybrid Public Key Encryption). |
| 211 |
/// |
| 212 |
/// Returns a tuple containing the encapsulated key and the ciphertext. |
| 213 |
pub fn hpke_seal( |
| 214 |
pub_key: &PublicKey, |
| 215 |
plaintext: &SecretBox, |
| 216 |
aad: &[u8], |
| 217 |
algo: &HpkeAlgorithm, |
| 218 |
) -> Result<(Vec<u8>, Vec<u8>), Error> { |
| 219 |
clear_stack_on_return(CLEAR_STACK_PAGES, || { |
| 220 |
pub_key.hpke_seal_internal(plaintext, aad, algo) |
| 221 |
}) |
| 222 |
} |
| 223 |
|
| 224 |
#[cfg(test)] |
| 225 |
mod tests { |
| 226 |
use super::*; |
| 227 |
use crate::algorithms::{AeadAlgorithm, KdfAlgorithm}; |
| 228 |
use bssl_crypto::hpke; |
| 229 |
|
| 230 |
#[test] |
| 231 |
fn test_decaps_wrapper() { |
| 232 |
let kem_algo = KemAlgorithm::DhkemX25519HkdfSha256; |
| 233 |
let (pk_r, sk_r) = generate_keypair(kem_algo).expect("KEM generation failed"); |
| 234 |
|
| 235 |
let hpke_kem = hpke::Kem::X25519HkdfSha256; |
| 236 |
let hpke_kdf = hpke::Kdf::HkdfSha256; |
| 237 |
let hpke_aead = hpke::Aead::Aes256Gcm; |
| 238 |
let params = hpke::Params::new(hpke_kem, hpke_kdf, hpke_aead); |
| 239 |
|
| 240 |
let (_sender_ctx, enc) = hpke::SenderContext::new(¶ms, pk_r.as_bytes(), b"") |
| 241 |
.expect("HPKE setup sender failed"); |
| 242 |
|
| 243 |
let result = decaps(&sk_r, &enc).expect("Decaps wrapper failed"); |
| 244 |
assert_eq!(result.as_slice().len(), 32); |
| 245 |
} |
| 246 |
|
| 247 |
#[test] |
| 248 |
fn test_decaps_unsupported() { |
| 249 |
let kem_algo = KemAlgorithm::DhkemX25519HkdfSha256; |
| 250 |
let (_pk_r, sk_r) = generate_keypair(kem_algo).expect("KEM generation failed"); |
| 251 |
|
| 252 |
let enc = [0u8; 32]; |
| 253 |
let algo = HpkeAlgorithm { |
| 254 |
kem: KemAlgorithm::Unspecified as i32, |
| 255 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 256 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 257 |
}; |
| 258 |
|
| 259 |
let result = hpke_open(&sk_r, &enc, &[], &[], &algo); |
| 260 |
assert!(matches!(result, Err(Error::UnsupportedAlgorithm))); |
| 261 |
} |
| 262 |
|
| 263 |
#[test] |
| 264 |
fn test_hpke_open_success() { |
| 265 |
let hpke_algo = HpkeAlgorithm { |
| 266 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 267 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 268 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 269 |
}; |
| 270 |
|
| 271 |
let kem_algo = KemAlgorithm::DhkemX25519HkdfSha256; |
| 272 |
|
| 273 |
let (pk_r, sk_r) = generate_keypair(kem_algo).expect("HPKE generation failed"); |
| 274 |
|
| 275 |
let pt = b"hello world"; |
| 276 |
let aad = b"additional data"; |
| 277 |
let info = b""; |
| 278 |
|
| 279 |
let hpke_kem = hpke::Kem::X25519HkdfSha256; |
| 280 |
let hpke_kdf = hpke::Kdf::HkdfSha256; |
| 281 |
let hpke_aead = hpke::Aead::Aes256Gcm; |
| 282 |
let params = hpke::Params::new(hpke_kem, hpke_kdf, hpke_aead); |
| 283 |
|
| 284 |
let (mut sender_ctx, enc) = hpke::SenderContext::new(¶ms, pk_r.as_bytes(), info) |
| 285 |
.expect("HPKE setup sender failed"); |
| 286 |
let ciphertext = sender_ctx.seal(pt, aad); |
| 287 |
|
| 288 |
let decrypted = |
| 289 |
hpke_open(&sk_r, &enc, &ciphertext, aad, &hpke_algo).expect("Decryption failed"); |
| 290 |
|
| 291 |
assert_eq!(decrypted.as_slice(), pt); |
| 292 |
} |
| 293 |
|
| 294 |
#[test] |
| 295 |
fn test_hpke_open_failure() { |
| 296 |
let hpke_algo = HpkeAlgorithm { |
| 297 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 298 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 299 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 300 |
}; |
| 301 |
|
| 302 |
let kem_algo = KemAlgorithm::DhkemX25519HkdfSha256; |
| 303 |
|
| 304 |
let (pk_r, sk_r) = generate_keypair(kem_algo).expect("HPKE generation failed"); |
| 305 |
|
| 306 |
let pt = b"hello world"; |
| 307 |
let aad = b"additional data"; |
| 308 |
let info = b""; |
| 309 |
|
| 310 |
let hpke_kem = hpke::Kem::X25519HkdfSha256; |
| 311 |
let hpke_kdf = hpke::Kdf::HkdfSha256; |
| 312 |
let hpke_aead = hpke::Aead::Aes256Gcm; |
| 313 |
let params = hpke::Params::new(hpke_kem, hpke_kdf, hpke_aead); |
| 314 |
|
| 315 |
let (mut sender_ctx, enc) = hpke::SenderContext::new(¶ms, pk_r.as_bytes(), info) |
| 316 |
.expect("HPKE setup sender failed"); |
| 317 |
let mut ciphertext = sender_ctx.seal(pt, aad); |
| 318 |
|
| 319 |
// Tamper with ciphertext |
| 320 |
if let Some(byte) = ciphertext.get_mut(0) { |
| 321 |
*byte ^= 1; |
| 322 |
} |
| 323 |
|
| 324 |
let result = hpke_open(&sk_r, &enc, &ciphertext, aad, &hpke_algo); |
| 325 |
assert!(matches!(result, Err(Error::HpkeDecryptionError))); |
| 326 |
} |
| 327 |
|
| 328 |
#[test] |
| 329 |
fn test_hpke_bad_aad() { |
| 330 |
let hpke_algo = HpkeAlgorithm { |
| 331 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 332 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 333 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 334 |
}; |
| 335 |
|
| 336 |
let kem_algo = KemAlgorithm::DhkemX25519HkdfSha256; |
| 337 |
|
| 338 |
let (pk_r, sk_r) = generate_keypair(kem_algo).expect("HPKE generation failed"); |
| 339 |
|
| 340 |
let pt = b"hello world"; |
| 341 |
let aad = b"foo"; |
| 342 |
let info = b""; |
| 343 |
|
| 344 |
let hpke_kem = hpke::Kem::X25519HkdfSha256; |
| 345 |
let hpke_kdf = hpke::Kdf::HkdfSha256; |
| 346 |
let hpke_aead = hpke::Aead::Aes256Gcm; |
| 347 |
let params = hpke::Params::new(hpke_kem, hpke_kdf, hpke_aead); |
| 348 |
|
| 349 |
let (mut sender_ctx, enc) = hpke::SenderContext::new(¶ms, pk_r.as_bytes(), info) |
| 350 |
.expect("HPKE setup sender failed"); |
| 351 |
let ciphertext = sender_ctx.seal(pt, aad); |
| 352 |
|
| 353 |
// Tamper with aad |
| 354 |
let tampered_aad = b"bar"; |
| 355 |
|
| 356 |
let result = hpke_open(&sk_r, &enc, &ciphertext, tampered_aad, &hpke_algo); |
| 357 |
assert!(matches!(result, Err(Error::HpkeDecryptionError))); |
| 358 |
} |
| 359 |
|
| 360 |
#[test] |
| 361 |
fn test_hpke_seal_success() { |
| 362 |
let hpke_algo = HpkeAlgorithm { |
| 363 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 364 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 365 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 366 |
}; |
| 367 |
let kem_algo = KemAlgorithm::DhkemX25519HkdfSha256; |
| 368 |
|
| 369 |
let (pk_r, sk_r) = generate_keypair(kem_algo).expect("HPKE generation failed"); |
| 370 |
|
| 371 |
let pt = SecretBox::new(b"hello world".to_vec()); |
| 372 |
let aad = b"additional data"; |
| 373 |
|
| 374 |
// Seal |
| 375 |
let (enc, ciphertext) = hpke_seal(&pk_r, &pt, aad, &hpke_algo).expect("HPKE seal failed"); |
| 376 |
|
| 377 |
// Decrypt to verify |
| 378 |
let decrypted = |
| 379 |
hpke_open(&sk_r, &enc, &ciphertext, aad, &hpke_algo).expect("Decryption failed"); |
| 380 |
assert_eq!(decrypted.as_slice(), pt.as_slice()); |
| 381 |
} |
| 382 |
|
| 383 |
#[test] |
| 384 |
fn test_generate_kem_success() { |
| 385 |
let algo = KemAlgorithm::DhkemX25519HkdfSha256; |
| 386 |
let (pub_key, _priv_key) = generate_keypair(algo).expect("KEM generation failed"); |
| 387 |
assert_eq!(pub_key.as_bytes().len(), 32); |
| 388 |
} |
| 389 |
|
| 390 |
#[test] |
| 391 |
fn test_generate_hpke_success() { |
| 392 |
let algo = KemAlgorithm::DhkemX25519HkdfSha256; |
| 393 |
|
| 394 |
let (pub_key, _priv_key) = generate_keypair(algo).expect("HPKE generation failed"); |
| 395 |
assert_eq!(pub_key.as_bytes().len(), 32); |
| 396 |
} |
| 397 |
|
| 398 |
#[test] |
| 399 |
fn test_generate_hpke_unsupported() { |
| 400 |
let algo = KemAlgorithm::Unspecified; |
| 401 |
|
| 402 |
let result = generate_keypair(algo); |
| 403 |
assert!(matches!(result, Err(Error::UnsupportedAlgorithm))); |
| 404 |
} |
| 405 |
} |