| 17 | } |
| 18 | |
| 19 | pub fn dh_decrypt(secret: [u8; 32], ciphertext: &[u8]) -> Result<Vec<u8>> { |
| 20 | // Extract components (matching JS implementation) |
| 21 | let ephemeral_pubkey = ciphertext |
| 22 | .get(..32) |
| 23 | .ok_or(anyhow!("Invalid ephemeral public key length"))? |
| 24 | .try_into() |
| 25 | .map_err(|_| anyhow!("Invalid ephemeral public key length"))?; |
| 26 | let iv = &ciphertext.get(32..44).ok_or(anyhow!("Invalid IV length"))?; |
| 27 | let ciphertext = &ciphertext |
| 28 | .get(44..) |
| 29 | .ok_or(anyhow!("Invalid ciphertext length"))?; |
| 30 | |
| 31 | // Derive shared secret using X25519 |
| 32 | let shared_secret = dh_agree(secret, ephemeral_pubkey); |
| 33 | |
| 34 | // Create AES-GCM cipher |
| 35 | let cipher = Aes256Gcm::new_from_slice(&shared_secret) |
| 36 | .map_err(|e| anyhow!("Failed to create cipher: {}", e))?; |
| 37 | |
| 38 | // Decrypt using AES-GCM |
| 39 | cipher |
| 40 | .decrypt(Nonce::<Aes256Gcm>::from_slice(iv), ciphertext.as_ref()) |
| 41 | .map_err(|e| anyhow!("Decryption failed: {}", e)) |
| 42 | } |
| 43 | |
| 44 | #[cfg(test)] |
| 45 | mod tests { |